Dangling pointers and double free
- by user151410
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