views:

597

answers:

7

Duplicate: What REALLY happens when you don’t free after malloc?

Let's say, for example:

int main()
{
  char* test = new char[50000];
  return 0;
}

What happens to the allocated memory after the program had finished? Does it get freed for other applications immediately? Or perhaps after some time? Or maybe it's lost to the system forever? Or does it get swapped to the disk never to return to RAM? Or maybe something completely different?

I would like to know what happens on the major 3 OS's: Windows (XP and up, if there are any differences), Linux, Mac OS X.

+1  A: 

It goes away, as in, the operating system cleans it up. Any memory the program asked for, the OS knows about, so when the program shuts down, any memory used by it gets freed, and is available for use by other programs. I believe it becomes available immediately.

Daniel Huckstep
+1  A: 

The OS should reclaim it for system memory once the process using it has finished.

workmad3
+1  A: 

Well in Windows the memory is freed by the operating system as the program closes. If it's a large amount of memory it might take some time.

As far I as remember from when I worked with various flavours of Unix it's the same for all operating systems.

ChrisF
A: 

The answer will of course depend on the operating system, but in general the OS will go through and sweep up any remaining allocated/mapped memory when the program terminates. In the case of Linux, the cleanup will be completed before the process terminates (enters Z state).

bdonlan
+2  A: 

On any O/S with a MMU (which includes Unix, Linux, OSX and the Windows NT family) the process has a data structure that is used to set up page mappings for tbe MMU. When the process is terminated this mapping is released and the pages are added to the Operating System's free pool.

On non protected-memory O/S platforms such as DOS or some realtime operating systems the memory may need to be explicitly freed and the O/S pool could possibly leak memory if it is not tidied up correctly.

ConcernedOfTunbridgeWells
A: 

All those moments will be lost in time...
like tears in rain

-- Roy Batty in Blade Runner

It depends to a great extent on the OS. Most OSes will free the memory for you, some won't. If you develop for a desktop OS now a days, then you can be quite sure that the memory will be freed. That is less so in embedded systems or mobile phones, where in cases the memory will actually get lost up to the next reboot of the OS.

David Rodríguez - dribeas