开发者

Freeing memory after use

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 r开发者_StackOverflow中文版elease 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜