some_id
some_id

Reputation: 29896

free() data blocks in C

When one uses free() in C, does freeing one pointer, free the contained pointers?

e.g. If a pointer points to an array of structures that each hold another array of Strings and some other fields. Will freeing the pointer to the array of structs ripple down and free all the data or will these other pointers be broken, leaving memory unreachable?

Thanks

Upvotes: 0

Views: 1373

Answers (2)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95509

No. It frees only the memory allocated in the corresponding call to malloc/calloc. The contained pointers, for all free knows, might not even be pointers; free doesn't know the structure of the data that gets passed to it. It only sees the raw memory address, and so cannot know if it contains pointers.

I should add that a good way to know if you are leaking memory or not is to test your program with the valgrind memcheck tool. It has a tool to automatically detect memory leaks.

Upvotes: 1

Gabe
Gabe

Reputation: 86718

The free function knows nothing of the data contained within the block being freed. If you have pointers to other data in that block, you must free them before you free the block. If you don't free them at all you will have a memory leak. If you free them afterwards, you could have heap corruption.

Upvotes: 2

Related Questions