Click to See Complete Forum and Search --> : [C] problem with free()


Navimel
June 28th, 2008, 09:47 AM
Hi,

i have a list which is my p, this list could have lot of elements.

I use this code below to free the memory at the end of my program.

A strange things happen, at certain point i dont know why, the execution stop at the free(app);

I have this problem just on Windows! On linux every thing is fine :ehh:

Does someone know what can cause this stop problem?


while(p!=NULL){
app=p;
free(app);
p=p->next;


}


thanks

Duoas
June 28th, 2008, 10:03 AM
Does

while (p != NULL) {
app = p;
p = p->next;
free( app );
}

fix it?

laserlight
June 28th, 2008, 10:04 AM
It looks like you used free(app) a little too early. It should probably be:
while(p!=NULL){
app=p;
p=p->next;
free(app);
}

Navimel
June 28th, 2008, 10:08 AM
thanks a lot i was going crazy :wave:

vijay.yande
July 2nd, 2008, 06:42 AM
may be freeing it reverse help

code_carnage
July 2nd, 2008, 07:32 AM
while(p!=NULL){
app=p;
free(app);
p=p->next;


}




Idea is when app=p; both are pointing to the same memory location.

and now you do free(app) hence memory pointed by app will be gone.
Since p also points to the same memory, hence memory pointed by p is also gone making it a dangling pointer and then you are trying to access the memory which no longer exists through the dangling pointer p.. Which lead to an UB and most likely a crash..