Why doesn't free(p) set p to NULL?

前端 未结 9 1105
一向
一向 2020-12-10 12:33

Any reasons why this can not be standard behavior of free()?

multiple pointers pointing to the same object:

#include 
#i         


        
9条回答
  •  情话喂你
    2020-12-10 12:49

    C function parameters are always passed by value, so in order to modify the pointer passed to free() you would need to pass a pointer to the pointer being deallocated, which can lead bugs caused by forgotten & operators.

    Secondly, if that pointer had any aliases, the programmer would still be responsible for nulling them out. I could see problems caused by programmers assuming that all references were set to NULL.

    Finally, it's not always necessary to set the pointer to NULL. Imagine a function which allocates some memory, does some work and frees it before returning. I could see how setting the pointer to NULL might not seem optimal.

提交回复
热议问题