Search code examples
c++visual-c++memory-leaksraii

Should RAII cause memory leaks?


#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

struct A
{
    A(char* p)
        : p(p)
    {}

    ~A()
    {   
        delete this->p;
    }

    char* p;
};

int main()
{
    A a(new char);
    _CrtDumpMemoryLeaks();
}

After running in debugging mode, the output window of Visual Studio 2012 shows:

Detected memory leaks!
Dumping objects ->
{142} normal block at 0x007395A8, 1 bytes long.
 Data: < > CD 
Object dump complete.

What's the cause?


Solution

  • Perhaps it's dumping the memory leaks before the destructor is actually called? Try:

    int main()
    {
         {
             A a(new char);
         }
         _CrtDumpMemoryLeaks();
    }
    

    I suggest using the standard's (or boost's) smart pointer classes, such as unique_ptr or shared_ptr, instead of dealing with new/delete directly with raw pointers.

    EDIT: Removed the suggestion to set the pointer to NULL, since delete deals with that.