Is it really important to free allocated memory if the program's just about to exit?

This question already has an answer here:


ANSWERS:


Generally, the OS will reclaim the memory, so no, you don't have to free() it. But it is really good practice to do it, and in some cases it may actually make a difference. Couple of examples:

  • You execute your program as a subprocess of another process. Depending on how that is done (see comments below), the memory won't be freed until the parent finishes. If the parent never finishes, that's a permanent leak.
  • You change your program to do something else. Now you need to hunt down every exit path and free everything, and you'll likely forget some.
  • Reclaiming the memory is of OS' volition. All major ones do it, but if you port your program to another system it may not.
  • Static analysis and debug tools work better with correct code.
  • If the memory is shared between processes, it may only be freed after all processes terminate, or possibly not even then.

By the way, this is just about memory. Freeing other resources, such as closing a file (fclose()) is much more important, as some OSes (Windows) don't properly flush the stream.



 MORE:


 ? Is necessary to do a free(string) before end a program?
 ? Memory leak in malloc
 ? Is there a reason to call delete in C++ when a program is exiting anyway?
 ? Does calling free or delete ever release memory back to the "system"
 ? When a program terminates what happens to the memory allocated using malloc that is not free'ed?
 ? Segmentation fault when malloc/free appear in loop in C
 ? Some memory seems to be left allocated after malloc() and free()
 ? Intricacies of malloc and free
 ? Puzzling behavior, malloc and free(), with libuv
 ? Simple test of malloc and free with int pointer causes double free or corruption error