Calling free on a pointer twice

前端 未结 4 1288
轻奢々
轻奢々 2021-02-04 03:07

I have been taught in lectures, that calling free() on a pointer twice is really, really bad. I know that it is good practice, to set a pointer to NULL

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 03:31

    To answer your first question,

    So why does it not know, whether a pointer it receives through free() has been freed yet or not?

    because, the specification for malloc() in C standard does not mandate this. When you call malloc() or family of functions, what it does is to return you a pointer and internally it stores the size of the memory location allocated in that pointer. That is the reason free() does not need a size to clean up the memory.

    Also, once free()-d, what happens with the actually allocated memory is still implelentation dependent. Calling free() is just a marker to point out that the allocated memory is no longer in use by the process and can be reclaimed and e re-allocated, if needed. So, keeping track of the allocated pointer is very needless at that point. It will be an unnecessary burden on the OS to keep all the backtracks.

    For debugging purpose, however, some library implementations can do this job for you, like DUMA or dmalloc and last but not the least, memcheck tool from Valgrind.

    Now, technically, the C standard does not specify any behaviour if you call free() on an already free-ed pointer. It is undefined behavior.

    C11, chapter §7.22.3.3, free() function

    [...] if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

提交回复
热议问题