双重释放或损坏(快速顶部)

17

当我执行时,我的代码的以下部分会给我这个消息:* glibc detected ./a.out: double free or corruption (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);
    }

这个程序片段的目的是什么?另外,temp2=(NODE *)malloc(sizeof(NODE)); temp2=first; 至少会造成内存泄漏。 - wildplasser
你应该检查 (first->ptr) != NULL。 - user1584773
fflush具有未定义的行为。如果您想要丢弃stdin上的数据,请读取并丢弃它们,但避免使用fflush。 - Abhineet
可能是如何跟踪“双重释放或破坏”错误的重复问题。 - Raedwald
1个回答

21

问题就在这里:

        temp2=first;

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

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

由于赋值之后无法释放,因此

仍然存在内存泄漏问题。

此外,您的代码可能还存在其他问题(其中一个问题是在输入流上不应该使用 ),但如果没有更多细节,很难确定。


@Abhineet:我认为Paul92不是故意的,看起来他只是打错了字。他本来想写“shouldn't”,但是没有按到“n”键。所以最后出现了“should't”,而你读成了“should”。 - Multisync

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接