简体   繁体   中英

Resource Consumption of MALLOC in a C Application

I am writing a C app and I use malloc to create data on the heap. Now while the application is active, this data is always persistant, so I never "free" the Malloc data.

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?

This is implementation-defined. Strictly following the C standard, you should free everything you've malloc 'd before the application terminates.

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. 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).

You should never explicitly free such memory. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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