1. 程式人生 > >當程序退出後,動態申請的內存會自動釋放嗎

當程序退出後,動態申請的內存會自動釋放嗎

you disk -m sign min aps call pen height

stackoverflow有人問了這麽一個問題,下面這段程序執行完畢後,malloc的內存會釋放嗎

[cpp] view plain copy
  1. <span style="font-size:18px;">int main () {
  2. int *p = malloc(10 * sizeof *p);
  3. *p = 42;
  4. return 0; //Exiting without freeing the allocated memory
  5. }</span>

贊數最多的這麽回答:

It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.

Relying on this is bad practice and it is better to free it explicitly. The issue isn‘t just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.
Relying on a feature of an operating system also makes the code less portable.

因此這些內存是會被大部分現代操作系統釋放掉的,這些系統包括

MacOS X, Linux, all recent version of Windows, and all currently manufactured phone handsets

一些老的系統不會釋放:

If you‘re programming on microcontrollers, on MacOS 9 or earler, DOS, or Windows 3.x, then you might need to be concerned about memory leaks making memory permenantly unavailable to the whole operating system.

解釋如下:

Most modern operating systems employ a memory manager, and all userland processes only see so-called virtual memory, which is not related to actual system memory in a way that the program could inspect. This means that programs cannot simply read another process‘s memory or kernel memory. It also means that the memory manager will completely "free" all memory that has been assigned to a process when that process terminates, so that memory leaks within the program do not usually "affect" the rest of the system (other than perhaps forcing a huge amount of disk swapping and perhaps some "out of memory" behaviour).

This doesn‘t mean that it‘s in any way OK to treat memory leaks light-heartedly, it only means that no single program can casually corrupt other processes on modern multi-tasking operating systems (deliberate abuse of administrative privileges notwithstanding, of course).

此外The Linux Programming Interface書中有這麽一段:

When a process terminates, all of its memory is returned to the system, including heap memory allocated by functions in the malloc package. In programs that allocate memory and continue using it until program termination, it is common to omit calls to free(), relying on this behavior to automatically free the memory. This can be especially useful in programs that allocate many blocks of memory, since adding multiple calls to free() could be expensive in terms of CPU time, as well as perhaps being complicated to code.

我們在學習C語言時,老師就告訴我們,動態開辟內存之後,要及時回收,不然就會造成內存泄漏。

現在想想內存泄漏是指在當前進程在堆中分配了空間後,完成了相關的操作,沒有及時釋放掉(不再需要此空間),並且進程沒有結束!

當程序退出後,動態申請的內存會自動釋放嗎