Originally Posted by
Kehyn
If I have to go in and free each element, how would I know how many elements I need to free?
This is a harder problem to create than you maybe think, but anyway.
One failsafe is: unallocated pointers are assigned NULL when declared:
if it's in a struct, initialize the members to NULL or you zero out the struct (which NULLs the pointers).
Next, de-allocated pointers are assigned NULL:
Code:
free(ptr);
ptr = NULL;
Finally, when cleaning-up: never free a NULL pointer, always free a non-NULL pointer:
Code:
if (ptr) { // NULL == FALSE, or 0. Everything else is TRUE.
free(ptr);
ptr = NULL;
}
This is not the most optimal method but it's cheap enough and works well.