Is there any point to freeing memory in an atexit() function?
I have a global variable that gets malloc'ed after startup. I could write an atexit() function to free it, but isn't the system going to reclaim all that memory when the program exits anyway?
Is there any benefit to being tidy and actively cleaning it up myself?
The atexit() function registers the given function to be called at normal process termination, either via exit(3) or via return from the program's main(). Functions so registered are called in the reverse order of their registration; no arguments are passed.
Return Value atexit returns 0 if successful, or a nonzero value if an error occurs.
You may call atexit() up to 32 times in a program. If you register more than one function in this way, they will be called in LIFO order: the last function registered will be the first one called when your program exists.
In all modern operating systems, you can safely assume that all memory will be freed when the program exits.
Seeing as malloc()
/free()
normally involve extensive data structures that exist in userspace, free()
ing memory when your program ends can actually be a performance drain. If parts of the data structure are paged to disk, they need to be loaded from disk only to be discarded!
Whereas if you terminate without free()
ing, the data paged out to disk can die in peace.
Of course free()
ing at other times is usually beneficial as further malloc()
s can re-use the space you freed and free()
might even unmap some memory which can then be used by other processes.
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