Is there any mechanism like destructors in C? Or is there another way to achieve it?
My requirement is that when a program terminates all memory allocated at runtime should be freed. I keep a list of memory that is allocated using malloc
.
Is there any mechanism like destructors in C? Or is there another way to achieve it?
My requirement is that when a program terminates all memory allocated at runtime should be freed. I keep a list of memory that is allocated using malloc
.
Another alternative is to write a memory manager.
The idea is that the memory manager allocates large blocks of memory and divides it into smaller pieces for the rest of the program to use. When the program terminates, the memory manager can just delete the large blocks.
That's the basic idea, although the memory manager may need to be more complex depending on the memory usage profile of the program.
There's a basic memory manager in the Doom source code you could examine: http://doom.wikia.com/wiki/Zone_memory
A very simple solution is not to use malloc
. This is an option adopted by some safety critical systems and they just use the stack.
Otherwise just terminate the program in a control fashion and tidy up during termination.
C++ uses RAII for managing resource lifetimes.
There is no such mechanism in C, Since you cannot have member functions for structures. Your main concern should be freeing memory allocations for reuse during the lifetime of the program rather than at the end of the lifetime. Once the program ends the OS will reclaim the leaked memory anyways.
Best way to do this in C is, to design your application to take care of lifetimes and code accordingly. This includes careful decision making of whether you really need dynamic memory allocations and if at all the lifetime of the allocated object should be well defined.
The operating system will take care of this. When a program terminates, the OS will reclaim all memory used by the process.
At application termination all memory allocated through malloc() will be freed unless the application becomes some kind of a zombie process. Normal termination should free all space otherwise.
The malloc() function uses operating system calls to allocate memory and when the process terminates the memory allocated to the process is reclaimed by the operating system.
I have seen cases of zombie processes under Windows in which a process stayed in memory hanging around until it was terminated via the Task Manager application.