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

前端 未结 18 1013
南旧
南旧 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:23

    Yes you are right, your example doesn't do any harm (at least not on most modern operating systems). All the memory allocated by your process will be recovered by the operating system once the process exits.

    Source: Allocation and GC Myths (PostScript alert!)

    Allocation Myth 4: Non-garbage-collected programs should always deallocate all memory they allocate.

    The Truth: Omitted deallocations in frequently executed code cause growing leaks. They are rarely acceptable. but Programs that retain most allocated memory until program exit often perform better without any intervening deallocation. Malloc is much easier to implement if there is no free.

    In most cases, deallocating memory just before program exit is pointless. The OS will reclaim it anyway. Free will touch and page in the dead objects; the OS won't.

    Consequence: Be careful with "leak detectors" that count allocations. Some "leaks" are good!

    That said, you should really try to avoid all memory leaks!

    Second question: your design is ok. If you need to store something until your application exits then its ok to do this with dynamic memory allocation. If you don't know the required size upfront, you can't use statically allocated memory.

提交回复
热议问题