Reputation: 4432
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)?
Upvotes: 1
Views: 2681
Reputation: 9208
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.
Upvotes: 16
Reputation: 91534
Memory 'allocation' has two distinct meanings that are commonly overlapped in questions like this.
the sbrk system call tell the kernel to get some more memory ready in case the process needs it. the memory is not actually mapped into the processes address space until immediately before it is written to. This is called demand paging. Typically the right to access this memory is never actually revoked by the operating system until the process exits. If memory becomes scarce then the kswapd (part of the kernel) will shuffle the least used parts off to disk to make room. The kernel can enforce a hard limit on the ammount of memory in a processes working set if you would like :)
the second context is what you are talking about when you call malloc/free. malloc keeps a list of available memory and hands chunks out to your functions when requested. if it detects that it doesnt have enough memory on hand to meet a request it will call sbrk to allow the process to access more.
when you look at the output of top you will see two numbers for a processes memory usage. One for the 'virtual size' and 'resident size', virtual size is the total amount that the process has requested access to. resident size is the amount that is actively being used by the process at the moment.
Upvotes: 1
Reputation: 62583
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.
Upvotes: 2
Reputation: 44804
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.
Upvotes: 1
Reputation: 38564
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.
Upvotes: 0
Reputation: 754615
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.
Upvotes: 0