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

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

    Bjarne Stroustrup discussing whether the delete operator should zero its operand. It's not the free() function, but it's a good discussion anyway. Consider points like:

    • What would be zeroed out if you said free(p + 1)?
    • What if there are two pointers to the memory? Why only set one to null if a dangling reference is still left behind?

    He also says it was intended but never happened with operator delete:

    C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.

提交回复
热议问题