问题描述
可能重复:结果
When您退出一个C程序,是的malloc-ED自动记忆中解脱出来?
这问题就来了我的脑海里,当我在阅读关于它是如何强制当谈到在C / C动态内存分配++使用分别删除/免费。我想如果内存分配持续超出了我的程序执行的终止,那么是的,它是强制性的;否则,为什么我不用担心释放分配的空间?是不是操作系统将与进程终止自动释放它吗?如何正确的我是谁?
我的问题是,能
This question came to my mind when i was reading about how compulsory it is to use delete/free respectively when it comes to dynamic memory allocation in C/C++. I thought if the memory allocation persisted beyond the termination of my program execution, then yes it is compulsory; otherwise, why do i have to worry about freeing up the allocated space? Isn't the OS going to free it up automatically with process termination? How right am i?My question is that can
int *ip = new int(8);
持续超过我的程序终止?
persist beyond the termination of my program?
推荐答案
简短的回答:没有。
龙答:第C除非你做的工作,使之做到++永远坚持的记忆。之所以可用内存是这样的:
Long answer: No. C++ will never persist memory unless you do the work to make it do so. The reason to free memory is this:
如果你没有空闲内存,但要分配它,你会在某个时候冒了出来。一旦你用完了,几乎任何事情都有可能发生。在Linux上,也许OOM杀手被激活,进程被杀死。也许OS页面,完全磁盘。也许你给Windows中出现蓝屏如果使用足够的内存。它几乎可以被认为是不确定的行为。另外,如果你泄漏内存,它只是选址在那里,未使用的,未发行的,直到你的进程终止没有人可以使用它。
If you don't free memory, but keep allocating it, you will run out at some point. Once you run out, almost anything can happen. On Linux, maybe the OOM killer is activated and your process is killed. Maybe the OS pages you completely to disk. Maybe you give a Windows box a blue screen if you use enough memory. It can almost be thought of as undefined behavior. Also, if you leak memory, it's just siting there, unused, unreleased, and no one can use it until your process terminates.
有另一个原因了。当你释放内存分配器,分配器可以保持它周围,而只是将其标记为可用。这意味着,下次你需要记忆的时候,它已经坐在那里等着你。这意味着有来电少进内核询问内存,提高性能,因为上下文切换效率非常低。
There's another reason too. When you release memory to the allocator, the allocator might keep it around, but just mark it as usable. That means that next time you need memory, it's already sitting there waiting for you. That means there are less calls into the kernel to ask for memory, increasing performance, as context switches are very inefficient.
编辑:C和C ++标准,甚至不给一个保证内存将被终止后OS清理。许多操作系统和编译器可能,但也不能保证。尽管如此,所有主要的桌面和移动操作系统(有可能是DOS和一些非常古老的嵌入式系统除外)做后清理进程的内存。
The C and C++ standards don't even give a guarantee that the memory will be cleaned up by the OS after termination. Many OSes and compilers may, but there is no guarantee. Despite this, all major desktop and mobile operation systems (with the exception of probably DOS and some very old embedded systems) do clean up a processes memory after it.
这篇关于可以在一个内存块使用操作符new分配/ malloc的持续超越程序执行的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!