The function for freeing an instance of struct Foo
is given below:
void DestroyFoo(Foo* foo)
{
if (foo) free(foo);
}
A
Unfortunately, this idea is just not working.
If the intent was to catch double free, it is not covering cases like the following.
Assume this code:
Foo *ptr_1 = (FOO*) malloc(sizeof(Foo));
Foo *ptr_2 = ptr_1;
free (ptr_1);
free (ptr_2); /* This is a bug */
The proposal is to write instead:
Foo *ptr_1 = (FOO*) malloc(sizeof(Foo));
Foo *ptr_2 = ptr_1;
DestroyFoo (&ptr_1);
DestroyFoo (&ptr_2); /* This is still a bug */
The problem is that the second call to DestroyFoo()
will still crash, because ptr_2
is not reset to NULL, and still point to memory already freed.