Dangling pointers and double free
Posted
by user151410
on Stack Overflow
See other posts from Stack Overflow
or by user151410
Published on 2010-04-01T20:17:14Z
Indexed on
2010/04/01
20:33 UTC
Read the original article
Hit count: 288
After some painful experiences, I understand the problem of dangling pointers and double free. I am seeking proper solutions. aStruct has a number of fields including other arrays.
aStruct *A=NULL, *B = NULL;
A = (aStruct*) calloc(1, sizeof(sStruct));
B = A;
free_aStruct(A);
...
//bunch of other code in various places.
...
free_aStruct(B);
Is there any way to write free_aStruct(X) so that free_aStruct(B) exists gracefully??
void free_aStruct(aStruct *X){
if (X ! = NULL){
if (X->a != NULL){free(X->a); x->a = NULL;}
free(X); X = NULL;
}
}
Doing above only sets A = NULL
when free_aStruct(A);
is called. B is now dangling.
How can this situation be avoided / remedied? Is reference counting the only viable solution? or, are there other "defensive" free approaches, to prevent free_aStruct(B);
from exploding?
Thanks,
Russ
© Stack Overflow or respective owner