Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top