. Advertisement .
..3..
. Advertisement .
..4..
I have the following c code, but I do not know how to find the correct result. Why has this problem occurred, and how can it be solved? Here is the code that I am running:
bool found= false;
int x=0;
for ( x=0; x<=312500; x++)
{
while (count <=32)
{
fscanf (file, "%d", &temp->num);
temp->ptr=NULL;
newNode = (NODE *)malloc(sizeof(NODE));
newNode->num=temp->num;
newNode->ptr=NULL;
if (first != NULL)
{
temp2=(NODE *)malloc(sizeof(NODE));
temp2=first;
while (temp2 != NULL && !found)
{
if (temp2->num == newNode->num)
{found=true;}
temp2= temp2->ptr;
}
free(temp2);
if (!found)
{
last->ptr=newNode;
last=newNode;
count=count+1;
}
}
else
{
first = newNode;
last = newNode;
count=count+1;
}
fflush(stdin);
}
And this is the error text I receive:
* glibc detected ./a.out: double free or corruption (fasttop): 0x08e065d0 **
The cause: I think here’s the issue:
In essence, you free temp2 first, not the memory that was allocated here:
,which is still a memory leak because it cannot be released after the assignment.
Additionally, your code probably has other issues (for example, you shouldn’t use
fflush
on an input stream), but it’s tough to determine without additional information.