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

前端 未结 9 1064
一向
一向 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.

    0 讨论(0)
  • 2020-12-10 12:56

    If it did, you would have to pass a pointer to a pointer to the function:

    int * p = malloc( sizeof( int ));
    free( & p );
    

    which I'm sure many people would get wrong.

    0 讨论(0)
  • 2020-12-10 12:57

    With reference to the quote from Stroustrup about delete, Peter Norvig also makes a similar remark. He writes (not about C++!):

    "Nothing is destroyed until it is replaced"
     - Auguste Comte (1798-1857) (on the need for revolutionary new
       theories (or on the need to do x.f = null in garbage-collected
       languages with destructors))
    

    In my C code, I find the following macro very useful:

    #define free(p) free((void *)(p)),(p)=NULL /* zero p */
    

    This, as written, uses its argument twice. But this isn't a problem, as any usage such as free(p++) or free(find_named_object("foo")) will give a compile-time error (lvalue required). And you can hide the macro by using (free)(p++), or by calling it something else e.g. FREE.

    0 讨论(0)
提交回复
热议问题