双重免费或腐败(fasttop)

Tha*_*lla 14 c coredump linked-list double-free

我的代码的以下部分在执行*glibc检测时给出了这个消息./a.out:双重免费或损坏(fasttop):0x08e065d0**

我已经多次通过代码,但我不能清楚看到我如何滥用 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);
    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*l92 17

问题出在这里:

        temp2=first;
Run Code Online (Sandbox Code Playgroud)

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

        temp2=(NODE *)malloc(sizeof(NODE));
Run Code Online (Sandbox Code Playgroud)

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

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

  • @Abhineet [`fflush()`](http://en.cppreference.com/w/c/io/fflush)有很多定义的行为.刷新*`stdin`*(或任何非输出流)是定义消失的地方,所以如果你要告诉人们"`fflush`有未定义的行为",也许要掌握准确性. (4认同)