17

The following section of my code gives me this messege when executing * glibc detected ./a.out: double free or corruption (fasttop): 0x08e065d0 **

i have gone through the code many times but i cant clealry see how i am misusing the free (temp2)

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);
    }
4

1 回答 1

21

问题在这里:

        temp2=first;

基本上,当你释放 temp2 时,你首先释放,而不是这里分配的内存:

        temp2=(NODE *)malloc(sizeof(NODE));

,这仍然是内存泄漏,因为在分配之后它不能再被释放。

此外,您的代码可能还有一些问题(一个是您不应该fflush在输入流上使用),但是如果没有更多细节,就无法判断。

于 2013-11-16T14:30:19.703 回答