问题描述
可能重复:结果
Is释放用C 退出程序时需要分配的内存
我读的网页。并在这句话就跑:
I was reading the page "Freeing Memory Allocated with malloc
" and ran across this sentence:
有,是在程序结束时释放块是没有意义的,因为所有的程序的空间被返还给系统进程终止时。
我知道是作者是想说,但应该不是一句是:
I realize what the author is trying to say, but shouldn't the sentence be:
有是在节目的最后释放块是没有意义的,因为所有的程序的空间被返还给系统进程终止时,虽然你还是应该确保你的程序释放所有malloc分配退出之前内存
或者是通常的做法是不是取消分配过程的终止前的记忆?
Or is it common practice to not de-allocate memory before the termination of the process?
推荐答案
我已经采取了大量的热量这一点,但我的立场是,把精力释放内存只是程序退出之前应该的是有害的的。一方面是额外的code维护和调试 - 但可能不会太多,所以这只是一个小问题。在更大的问题是实际效果。
I've taken a lot of heat for this, but my position is that putting effort into freeing memory just before program exit should be Considered Harmful. For one thing it's extra code to maintain and debug - but probably not too much, so that's only a small issue. The much larger issue is practical effects.
假设你有一个的分配复杂/深层数据结构的长期存在的程序 - 作为一个很好的例子,认为网络浏览器。这可能是因为许多这些数据尚未在使用了一段时间,并且进一步,它的被交换到磁盘。如果你只是退出
,磁盘上的交换出的数据只被标记为未使用的,并不会再感动。但是,如果你走过你的程序的所有的数据结构来释放他们,你会接触的每一个换出页的,从而导致:
Suppose you have a long-lived program that's allocated complex/deep data structures - as a good example, think of a web browser. It's likely that much of this data has not been used in a while, and further that it's been swapped to disk. If you just exit
, the swapped-out data on disk is simply marked unused and never touched again. But if you walk through all your program's data structures to free them, you will touch every single swapped-out page, causing:
- 磁盘访问读取换出的数据
- 从内存的其他程序的真正重要的数据驱逐
- 和相应的磁盘访问换出上述数据属于其他程序。
所有这些废弃物的:
- 用户的时间
- 在HDD穿(或更糟的是,在SSD /闪存)
此行为是容易观察到,如果你有足够的臃肿的桌面应用程序(火狐,OpenOffice的,GIMP等或Windows当量)得到它的交换超载你的系统,然后尝试关闭其中之一。你会花几秒钟(甚至〜30秒,它的交换已经够糟糕),等待它退出。如果程序刚刚叫退出
直接(检查未保存的文档和诸如此类的东西后),它会立即关闭。
This behavior is easily observable if you overload your system with enough bloated desktop apps (Firefox, OpenOffice, GIMP, etc. or Windows equivalents) to get it swapping, then try to close one of them. You'll spend several seconds (maybe even ~30 sec it the swapping is bad enough) waiting for it to exit. If the program had just called exit
directly (after checking for unsaved documents and whatnot) it would have closed immediately.
这篇关于目前在程序结束时释放块是没有意义的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!