0
#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?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

2 Answers2

7

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.

miguel.martin
  • 1,626
  • 1
  • 12
  • 27
5

You're dumping the memory before the destructor has had a chance to run, i.e. before the end of the block. Try this and see the difference:

int main()
{
    {
        A a(new char);
    }
    _CrtDumpMemoryLeaks();
}
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622