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

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

提交回复
热议问题