Click here to Skip to main content
15,910,009 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Suppose I have a main() function with only one malloc statement allocating say some 1 gb memory. Also say my system has 1 gb of ram.

C++
main()
{
    malloc(1gb)

    return(0)
}


The program above exits without freeing the memory.

In this case will the 1 gb of heap memory be returned to system on above process termination or has the heap memory permanently leaked and will be available only on system reboot?

I mean if say we start some another process or say the same process again then will they be able to get the 1 gb if heap again?
Posted

All modern operating systems will reclaim all heap memory when the application ends, but embedded systems may not - it depends on how they are written.
 
Share this answer
 
The memory will be returned to the free memory pool (although, it would be possible to make an OS that did not, but I'm sure Windows, Linux, and OSX manage their memory intelligently enough to reclaim it), because it is given to that process, and when the process is terminated the OS reclaims all resources used by the application.

If you start the same process, it will have to be allocated again, but assuming the memory hasn't been allocated to another process it shouldn't be an issue to do so. It's unlikely you will get the exact same memory again though, because the OS is constantly allocating memory to processes as they request it.

For another process, it depends. If the memory was shared, then it won't be reclaimed, because the other process is still using it. If you mean another process launching afterwards, then it can have that memory allocated to it by the OS if it's free (and it will be if the application shown above has exited).

I think there is (or was, it may no longer be possible) a way to allocate memory that the OS would not reclaim in Windows, leading to a memory leak until reboot, but I don't remember what it was. As for other OS's, I'm not sure, each manages memory in their own way.
 
Share this answer
 
Comments
Nelek 25-Oct-12 13:36pm    
Nice answer :)
Sergey Alexandrovich Kryukov 25-Oct-12 15:12pm    
Agree, my 5, too.
--SA
Nope, OS are smart, they do a lot of cleanup when a process terminates (releases memory, file handles, etc.)
Some programmers even relies on that.
 
Share this answer
 
Comments
Nelek 25-Oct-12 13:37pm    
Specially the klingons programmers ;P
Sergey Alexandrovich Kryukov 25-Oct-12 15:11pm    
Short and to the point, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900