What REALLY happens when you don't free after malloc?

前端 未结 18 781
南旧
南旧 2020-11-22 01:32

This has been something that has bothered me for ages now.

We are all taught in school (at least, I was) that you MUST free every pointer that is allocated. I\'m a

18条回答
  •  长发绾君心
    2020-11-22 02:11

    You are correct, no harm is done and it's faster to just exit

    There are various reasons for this:

    • All desktop and server environments simply release the entire memory space on exit(). They are unaware of program-internal data structures such as heaps.

    • Almost all free() implementations do not ever return memory to the operating system anyway.

    • More importantly, it's a waste of time when done right before exit(). At exit, memory pages and swap space are simply released. By contrast, a series of free() calls will burn CPU time and can result in disk paging operations, cache misses, and cache evictions.

    Regarding the possiblility of future code reuse justifing the certainty of pointless ops: that's a consideration but it's arguably not the Agile way. YAGNI!

提交回复
热议问题