Should one really set pointers to `NULL` after freeing them?

前端 未结 10 1087
庸人自扰
庸人自扰 2020-11-28 03:27

There seem to be two arguments why one should set a pointer to NULL after freeing them.

Avoid crashing when double-freeing pointers.

Short

10条回答
  •  被撕碎了的回忆
    2020-11-28 03:59

    If the pointer is going to be reused then is should be set back to 0(NULL) after use even if the object it was pointing is not freed from the heap. This allows for valid checking against NULL like if (p){ //do something}. Also just because you free an object whose address the pointer is pointing to doesn't mean the pointer is set 0 after calling on delete keyword or free function at all.

    If the pointer is used once and it is part of a scope which makes it local, then there is not need to set it to NULL being that it will be disposed of from the stack after the function returns.

    If the pointer is a member (struct or class), you should set it to NULL after freeing the object or objects on a double pointer again for valid checking against NULL.

    Doing this will help you alleviate the headaches from invalid pointers like '0xcdcd...' and so on. So if the pointer is 0 then you know it is not pointing to an address and can make sure that the object is released from the heap.

提交回复
热议问题