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);
    }
James M
  • 18,506
  • 3
  • 48
  • 56
Thair Abdalla
  • 279
  • 1
  • 5
  • 16
  • What is the _purpose_ of this program fragment ? BTW: `temp2=(NODE *)malloc(sizeof(NODE)); temp2=first;` will _at least_ leak memory. – wildplasser Nov 16 '13 at 14:25
  • You should check (first->ptr) != NULL – user1584773 Nov 16 '13 at 14:28
  • fflush have undefined behavior. If you want to discard data on stdin, read them and discard but avoid the usage of fflush. – Abhineet Nov 16 '13 at 14:39
  • Possible duplicate of [How to track down a "double free or corruption" error](https://stackoverflow.com/questions/2902064/how-to-track-down-a-double-free-or-corruption-error) – Raedwald Dec 06 '18 at 13:25

1 Answers1

21

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.

Paul92
  • 8,827
  • 1
  • 23
  • 37
  • @Abhineet: I don't think Paul92 meant to; to me it looks like he just made a typo. He meant to write *shouldn't* but didn't hit the `n`. So what came out was *should't* which you read as *should*. – Multisync Jun 19 '17 at 13:51