I have been trying to free memory allocated via malloc()
using free()
.
Some of the structs it does free but leaves some the way they were a
The only reason free()
would fail is if the pointer you give it does not dereference to allocated heap. This behavior is clearly defined, free()
will either work, or your program will halt due to an access violation.
It is good practice to re-initialize your pointers after freeing them, for just this purpose. This lets you:
Make sure you don't allocate on top of an already allocated pointer (thus losing the reference to the original blocks and causing a leak) (realloc() notwithstanding).
Make sure you don't free recently freed memory, or memory that was never allocated
Both become easy by testing to see if the pointer is initialized (or, NULL).
It's best to just do this manually and get in the habit of doing so. I have seen some very convoluted ways of re-implementing free()
so that re-initializes the pointer automatically, like this little gem that also attempts avoid freeing memory that wasn't allocated:
void safe_free(void **p)
{
if (*p != NULL) {
free(*p);
*p = NULL;
}
}
Please, don't use that code, it will break horribly on strict platforms due to dereferencing a type punned pointer. Additionally, what if the pointer is a string literal?
Instead, just make sure you keep track of your pointers and initialize them after freeing.