double free or corruption (fasttop)

邮差的信 提交于 2019-12-03 16:14:19

问题


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

回答1:


The problem is here:

        temp2=first;

Basically, when you free temp2, you free first, not the memory allocated here:

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

, which remains a memory leak, because after the assignment it can't be freed anymore.

Also, your code has probably some more problems (one is that you shouldn't use fflush on an input stream), but without some more details, it's impossible to tell.



来源:https://stackoverflow.com/questions/20019512/double-free-or-corruption-fasttop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!