views:

595

answers:

7

If you do not free memory that you malloc'd in a C program under Linux, when is it released? After the program terminates? Or is the memory still locked up until an unforseen time (probably at reboot)?

+8  A: 

Yes, the memory is freed when the process terminates.

McWafflestix
A: 

The memory is released from the point of the program when it exits. It is not tied up in any way after that and can be reused by other processes.

JaredPar
A: 

modern operating systems will release all memory allocated by a process when that process is terminated. The only situations where that might not be true, would probably be in very old operating systems (perhaps DOS?) and some embedded systems.

Carson Myers
A: 

In Linux (and most other Unixes) when you invoke a program from a command shell, it creates a new process to run that program in. All resources a process reserves, including heap memory, should get released back to the OS when your process terminates.

T.E.D.
+15  A: 

Memory allocated by malloc() is freed when the process ends. However memory allocated using shmget() is not freed when the process ends. Be careful with that.

Edit:

mmap() is not shmget() read about the difference here: http://www.opengroup.org/onlinepubs/000095399/functions/mmap.html http://www.opengroup.org/onlinepubs/009695399/functions/shmget.html

They are different system calls, which do very different things.

elcuco
Most mmap()'d memory - I think all - is released on process exit.
Jonathan Leffler
`mmap()` is not `shmget()` read about the difference here:http://www.opengroup.org/onlinepubs/000095399/functions/mmap.htmlhttp://www.opengroup.org/onlinepubs/009695399/functions/shmget.html
elcuco
+2  A: 

malloc()ed memory is definitely freed when the process ends, but not by calling free(). it's the whole memory mapping (presented to the process as linear RAM) that is just deleted from the MMU tables.

Javier
That makes perfect sense. +1
Jamie
+1  A: 
Arthur Ulfeldt