segunda-feira, 7 de maio de 2012

Never free() before you exit()

Due to a recently bug in my ZPUino programmer while running on Windows 7, which was caused by an invalid free() just before exit() the program, I came to the conclusion that all those free() before exiting are absurd under the operating systems we use.

Truth is all resources (non-shared) by your application will be released when the program exits. The memory allocation routines and algorithms run almost exclusively on your program domain (such as *alloc() in "C", and "new()" in C++), and there's no direct connections between those allocators and the chunks they allocate (all goes into a space called heap). So, when your program exits, all "heap" allocated by it will be lost, independently of how many malloc() you called, on how many new() you did [side note: on C++ you would still have to call all destructor eventually, but not release memory per-se].

The way your operating system allocates heap space (memory) for your application is often done using very simple methods like brk()/sbrk() on Linux / UNIX. And HeapAlloc() and friends on Windows. The management of this big memory area is done by your application itself (although using userspace OS methods to ease your path, like malloc() ).
When you're leaving the program, if you free() all of your memory, your application will:
a) Spend a whole lot of CPU cycles going through all your alloc() tables, eventually reclaiming memory space to the OS,
b) Release everything to the OS.

Why do a) ? Just spending CPU cycles, and power. OS does not know how you manage your memory (it does not have to), so it's a pretty much useless step.
So, if you're to exit your application, just forget memory allocation. Your OS will free all of your memory, despite you "freeing" it yourself or not. And, more important, there's absolutely no difference if you do free() it, or not.

Alvie

Sem comentários:

Enviar um comentário