简体   繁体   English

C应用中MALLOC的资源消耗

[英]Resource Consumption of MALLOC in a C Application

I am writing a C app and I use malloc to create data on the heap. 我正在编写一个C应用程序,我使用malloc在堆上创建数据。 Now while the application is active, this data is always persistant, so I never "free" the Malloc data. 现在,当应用程序处于活动状态时,此数据始终是持久的,因此我永远不会“释放”Malloc数据。

My question is: will this memory be automatically freed when the application terminates, or must I execute free() manually at the completion of my application? 我的问题是:当应用程序终止时,是否会自动释放此内存,或者我必须在完成应用程序时手动执行free()?

This is implementation-defined. 这是实现定义的。 Strictly following the C standard, you should free everything you've malloc 'd before the application terminates. 严格按照C标准,你应该free所有你已经malloc “d应用程序终止之前。

Any modern general-purpose operating system, however, will clean up after you, so this is only relevant in some embedded, old-fashioned, or otherwise exotic environments. 但是,任何现代通用操作系统都会在您之后进行清理,因此这仅适用于某些嵌入式,老式或其他异域环境。

As a point of style, do try to free every allocated block. 作为一种风格,尝试free每个分配的块。 It gets you in the habit of writing clean code and preventing memory leaks. 它让你养成编写干净代码和防止内存泄漏的习惯。

It will be freed. 它将被释放。 This is the wonders of the "process" abstraction. 这是“过程”抽象的奇迹。 All the resources and memory owned by this running process is freed upon termination. 此运行进程拥有的所有资源和内存在终止时释放。

Note that it took some time to come up with this abstraction, but it is a really nice sandbox for a system. 请注意,花了一些时间才能提出这种抽象,但对于一个系统来说,这是一个非常好的沙箱。 In fact, killing processes is even used as a last resort to try to fix buggy programs that have leaks or degraded performance as they execute for days (it is called with the pretty name of "Process Rejuvenation" , and even exists in conferences and journals, but is really an admittance of a bad design or coding). 事实上,杀戮过程甚至被用来作为最后的手段来尝试修复在执行数天时出现泄漏或性能下降的错误程序(它的名称为“Process Rejuvenation” ,甚至存在于会议和期刊中) ,但实际上是一个糟糕的设计或编码的准入)。

You should never explicitly free such memory. 你永远不应该明确free这样的记忆。 At best it will give you no benefit, and at worst it will swap a lot of swapped-out data back into memory just to inspect some bookkeeping pointers and then discard it, thrashing the user's hard drive for no purpose. 它充其量只会给你带来任何好处,最糟糕的是它会将大量换出的数据交换回内存,只是为了检查一些簿记指针然后丢弃它,无缘无故地摧毁用户的硬盘。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM