views:

150

answers:

6

I have a command line C program for which I use the calloc() function to assign some memory for a struct which also has a struct in it with some memory assigned.

If I use the free() function to release the memory from the parent struct, will it also release the memory from the child struct?

Or should I release the memory from the child struct first?

+6  A: 

No, you need to release the memory from the child first.

Trent
+11  A: 

Its a simple rule, for every memory allocation you do, you have to explicitly release the memory yourself. So, you need to release the child memory yourself.

Naveen
And you need to at least grab the pointers to the child memory before freeing the parent structure - to ensure the code does not access freed memory. Alternatively, simply release the child structures before the parents - a case for post-order traversal of any tree structures you have.
Jonathan Leffler
A: 

It depends on what happens to the structure after the free. As long as a structure is not referenced after free() all is well. If free is called and then some code makes reference to the freed memory, very difficult-to-debug things might happen. Don't do the latter.

wallyk
A: 

There may be no need to free the memory at all since all allocated memory is released when the program terminates. You only need to call free() if you wish to conserve memory usage.

Mick Sharpe
What if the parent struct is created and deleted inside a loop?
egrunin
A: 

I think it's worth mentioning that, for short-running command line tools, it often doesn't matter. Once your program is finished running, the operating system will reclaim all the memory, anyway. However, if this is a tool that runs for an indeterminate length of time, you do need to worry about memory management, and the other answers have good advice.

Sean Devlin
I think it's bad advice to say 'let the OS take care of it', even if it is for a small program. You don't want to get in the habit of writing leaky code.
Trent
+1  A: 

Always release the child structs first. It may be wise to write functions that will free each type of struct to simplify life farther up the line. If structTypeA contains structTypeB and StructTypeC, this would allow you to simply call freeStructTypeA(pointer-to-sTA-instance) and have the function take care of freeing all the child structs before freeing structTypeA itself.

On a related note, you would do well to try running your code through valgrind to ensure you're freeing all your memory correctly.

Sean
I completely agree. If a struct contains dynamically-allocated children, it is usually easiest to write a function to handle freeing the struct and all associated child objects.
bta