Possible Duplicate:
Is freeing allocated memory needed when exiting a program in C
I was reading the page "Freeing Memory Allocated with malloc
" and ran across this sentence:
There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates.
I realize what the author is trying to say, but shouldn't the sentence be:
There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates, although you should still make sure you program frees all malloc'ed memory before exiting.
Or is it common practice to not de-allocate memory before the termination of the process?
I've taken a lot of heat for this, but my position is that putting effort into freeing memory just before program exit should be Considered Harmful. For one thing it's extra code to maintain and debug - but probably not too much, so that's only a small issue. The much larger issue is practical effects.
Suppose you have a long-lived program that's allocated complex/deep data structures - as a good example, think of a web browser. It's likely that much of this data has not been used in a while, and further that it's been swapped to disk. If you just exit
, the swapped-out data on disk is simply marked unused and never touched again. But if you walk through all your program's data structures to free them, you will touch every single swapped-out page, causing:
All of this wastes:
This behavior is easily observable if you overload your system with enough bloated desktop apps (Firefox, OpenOffice, GIMP, etc. or Windows equivalents) to get it swapping, then try to close one of them. You'll spend several seconds (maybe even ~30 sec it the swapping is bad enough) waiting for it to exit. If the program had just called exit
directly (after checking for unsaved documents and whatnot) it would have closed immediately.
(This is a highly subjective answer, so take it how you will.)
I think it's good practice in case you end up adding to the process, in which case you might want to free up the memory after all.
I think it's always good to hold dynamic memory only as long as you need it, and then freeing it up. I usually like to write free
in my code immediately after I write malloc
, and then put whatever code I need in between.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With