Search code examples
cmemory-managementgarbage-collection

Are there any downsides to only free-ing dynamically allocated memory at the end of program execution?


I’ve implemented a data structure that defers the free-ing of dynamically-allocated memory until the end of the program. Essentially, it’s an allocation stack that keeps track of all heap-allocations. Then, at the end of the program, all allocations are freed. I can see the obvious pro to this being the fact that I don’t have to worry about free-ing pointers or if I have an accidental double-free. The downside, from what I’ve seen, is that heap memory usage only increases as the program continues execution. Are there any other downsides to this?


Solution

  • The downside is that your program will use more total memory than it actually needs, since every allocation will increase the total memory used, rather than reusing memory that was previously freed. Depending on how long the program runs, this could add up, and slow things down.

    As an example, imagine if you did this in a text editor where you edit many files. When you close a window, all the memory associated with that file will still be allocated, even though it's not being used for anything. If you're like me, you keep the editor open all the time, editing various files and closing the ones you no longer need. If it didn't free all the allocations when closing a file, the memory use could grow enormously, since I rarely exit.

    Freeing memory as soon as it's no longer needed allows the heap manager to reuse that memory rather than increasing the total memory footprint of the process. While modern systems have lots of memory, both physical and virtual, it's not infinite, and if several large applications worked the way you describe you could run into problems.

    There are also applictions that are intended never to exit, e.g. webservers and system daemons.

    Do you have a DVR that reboots every day? One possible reason is because the programmers took shortcuts and don't free memory when it's not needed, so the memory just keeps growing, and they reboot to clear the memory before it runs out.