Is it good practice to NULL a pointer after deleting it?

后端 未结 18 822
猫巷女王i
猫巷女王i 2020-11-22 11:28

I\'ll start out by saying, use smart pointers and you\'ll never have to worry about this.

What are the problems with the following code?

<         


        
18条回答
  •  清酒与你
    2020-11-22 11:53

    I always set a pointer to NULL (now nullptr) after deleting the object(s) it points to.

    1. It can help catch many references to freed memory (assuming your platform faults on a deref of a null pointer).

    2. It won't catch all references to free'd memory if, for example, you have copies of the pointer lying around. But some is better than none.

    3. It will mask a double-delete, but I find those are far less common than accesses to already freed memory.

    4. In many cases the compiler is going to optimize it away. So the argument that it's unnecessary doesn't persuade me.

    5. If you're already using RAII, then there aren't many deletes in your code to begin with, so the argument that the extra assignment causes clutter doesn't persuade me.

    6. It's often convenient, when debugging, to see the null value rather than a stale pointer.

    7. If this still bothers you, use a smart pointer or a reference instead.

    I also set other types of resource handles to the no-resource value when the resource is free'd (which is typically only in the destructor of an RAII wrapper written to encapsulate the resource).

    I worked on a large (9 million statements) commercial product (primarily in C). At one point, we used macro magic to null out the pointer when memory was freed. This immediately exposed lots of lurking bugs that were promptly fixed. As far as I can remember, we never had a double-free bug.

    Update: Microsoft believes that it's a good practice for security and recommends the practice in their SDL policies. Apparently MSVC++11 will stomp the deleted pointer automatically (in many circumstances) if you compile with the /SDL option.

提交回复
热议问题