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

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

    What's this maniac thing with zero ? There are other numbers !

    Why should a free pointer should contain zero more than any other distinguished value ?

    Practically, in my C++ code I often use watchdog objects and when freeing a pointer reset it not to zero but to the watchdog. That has the added benefit that the methods of the object can still be called with the existing interface and is much more secure and efficient that resetting pointer to zero (it avoid testing objects for zero, I just call the object).

    If a free like function say zfree(void * & p) would set p to zero it would forbid my watchdog style (or at least would'nt help).

    And as others pointer out , what would be the point to reset a pointer to zero if it goes out of scope ? Just useless code. And what if there is other pointers that contain the same adress, etc.

提交回复
热议问题