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:
- disk access to read the swapped-out data
- eviction of other programs' actually-important data from memory
- and corresponding disk access to swap out said data belonging to other programs.
All of this wastes:
- the user's time
- wear on the HDD (or even worse, on SSD/flash)
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.