程序终止后动态分配内存

jus*_*ugh 23 c c++ malloc memory-leaks memory-management

当包含动态分配的内存(使用malloc/new)而没有空闲/删除调用的C/C++程序终止时,动态分配的内存会发生什么?操作系统是否收回内存或者其他程序无法访问该内存?

Ken*_*oom 35

I don't think that there are any guarantees in the language standard, but modern operating systems which support sparse virtual memory and memory protection (such as MacOS X, Linux, all recent version of Windows, and all currently manufactured phone handsets) automatically clean up after badly-behaved processes (when they terminate) and free the memory for you. The memory remains unavailable, however as long as the program is running.

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.


Ker*_* SB 9

大多数现代操作系统都使用内存管理器,并且所有用户空间进程只能看到所谓的虚拟内存,它与程序可以检查的方式与实际系统内存无关.这意味着程序不能简单地读取另一个进程的内存或内核内存.这也意味着内存管理器将完全"释放"该进程终止时分配给进程的所有内存,以便程序中的内存泄漏通常不会"影响"系统的其余部分(除了可能强制执行大量的磁盘交换,也许还有一些"内存不足"的行为.

这并不意味着以任何方式可以轻松地处理内存泄漏,这只意味着没有任何单个程序可以随意破坏现代多任务操作系统上的其他进程(当然,故意滥用管理权限).


Mik*_*wan 6

简答:是的,操作系统会释放这个记忆.

大多数操作系统都会释放这些内存,但依赖此行为是不好的做法.某些操作系统不会释放此内存.例如,嵌入式系统.为了便于携带,请始终释放您分配的所有内存.

  • 通常只有*执行完成后* (2认同)