C++ small gotcha – 2


What’s wrong with the below code:

// a wrapper class which holds memory that’s allocated

// by using new []

template<class T>

class ArrayWrapper

{

public:

    ArrayWrapper(T* pData = NULL)

    {

        m_pData = pData;

    }

 

    ~ArrayWrapper()

    {

        delete [] m_pData;

    }

private:

    T* m_pData;

};

 

 

// code that use this class

{

    ArrayWrapper<WCHAR> buffer;

    buffer = new WCHAR[20];

}

 

Answer:

The first statement creates a new ArrayWrapper<WCHAR> object buffer which is initialized with NULL. The second statement create a temporary object, which is initialized with the address that is returned by the operator new, then the compiler copy the temporary object to buffer, then it call the destructor of the temporary object, this causes the memory to be freed. When the buffer object is out of scope, the same memory will be freed again and you have a double free issue.

 


Comments (1)

  1. Saphira says:

    Hence C++ "The rule of three"

Skip to main content