NULL pointer is the same as deallocating it?

前端 未结 11 2537
一个人的身影
一个人的身影 2021-02-18 18:29

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

For instance:

相关标签:
11条回答
  • 2021-02-18 19:00

    Under most circumstances, that will cause a memory leak in your process. You have several options for managing memory in C++.

    1. Use a delete to manually free memory when you're done with it. This can be hard to get right, especially in the context of exception handling.

    2. Use a smart pointer to manage memory for you (auto_ptr, shared_ptr, unique_ptr, etc.)

    3. C++ does not come with a garbage collector, but nothing prevents you from using one (such as the Boehm GC) if you want to go down that route.

    0 讨论(0)
  • 2021-02-18 19:02

    This is a classic leak. As you say, the memory remains allocated but nothing is referencing it, so it can never be reclaimed - until the process exits.

    The memory should be deallocated with delete - but using a smart pointer (e.g. std::auto_ptr or boost::shared_ptr (or tr1::shared_ptr) to wrap the pointer is a much safer way of working with pointers.

    Here's how you might rewrite your example using std::auto_ptr:

    std::auto_ptr a( new MyClass() );
    
    /*...do something in the meantime...*/
    
    a.reset();
    

    (Instead of the call to reset() you could just let the auto_ptr instance go out of scope)

    0 讨论(0)
  • 2021-02-18 19:05

    By assigning NULL to the pointer you will not free allocated memory. You should call deallocation function to free allocated memory. According to C++ Standard 5.3.4/8: "If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete". I could suggest the following function to safely delete pointers (with assigning NULL to them):

    template<typename T>
    inline void SafeDelete( T*& p )
    {
        // Check whether type is complete.
        // Deleting incomplete type will lead to undefined behavior
        // according to C++ Standard 5.3.5/5.
        typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
        (void) sizeof(type_must_be_complete);
    
        delete p;
        p = NULL;
    }
    
    0 讨论(0)
  • 2021-02-18 19:06

    That is a memory leak. You have to delete memory you allocate manually.

    0 讨论(0)
  • 2021-02-18 19:06

    C++ does't have garbage collector, like some other languages has (Java, C#, ...) so you must delete allocaled objects yourself.

    0 讨论(0)
提交回复
热议问题