Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing in an atexit()

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?

like image 418
Matt Avatar asked Oct 23 '08 19:10

Matt


People also ask

What does atexit() do?

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.

What does atexit return?

Return Value atexit returns 0 if successful, or a nonzero value if an error occurs.

Is it possible to call atexit () function more than once in AC program?

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.


2 Answers

In all modern operating systems, you can safely assume that all memory will be freed when the program exits.

like image 183
JesperE Avatar answered Sep 20 '22 14:09

JesperE


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.

like image 29
Artelius Avatar answered Sep 21 '22 14:09

Artelius