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

前端 未结 18 1058
南旧
南旧 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条回答
  •  Happy的楠姐
    2020-11-22 02:12

    I completely disagree with everyone who says OP is correct or there is no harm.

    Everyone is talking about a modern and/or legacy OS's.

    But what if I'm in an environment where I simply have no OS? Where there isn't anything?

    Imagine now you are using thread styled interrupts and allocate memory. In the C standard ISO/IEC:9899 is the lifetime of memory stated as:

    7.20.3 Memory management functions

    1 The order and contiguity of storage allocated by successive calls to the calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation.[...]

    So it has not to be given that the environment is doing the freeing job for you. Otherwise it would be added to the last sentence: "Or until the program terminates."

    So in other words: Not freeing memory is not just bad practice. It produces non portable and not C conform code. Which can at least be seen as 'correct, if the following: [...], is supported by environment'.

    But in cases where you have no OS at all, no one is doing the job for you (I know generally you don't allocate and reallocate memory on embedded systems, but there are cases where you may want to.)

    So speaking in general plain C (as which the OP is tagged), this is simply producing erroneous and non portable code.

提交回复
热议问题