What happens to memory that is not freed after end

2020-02-09 08:33发布

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.

7条回答
\"骚年 ilove
2楼-- · 2020-02-09 08:54

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.

查看更多
【Aperson】
3楼-- · 2020-02-09 08:55

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.

查看更多
Melony?
5楼-- · 2020-02-09 09:12

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).

查看更多
闹够了就滚
6楼-- · 2020-02-09 09:15

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.

查看更多
叛逆
7楼-- · 2020-02-09 09:17

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

查看更多
登录 后发表回答