How to detect memory leaks in MFC?

MFC framework has bult-in support for detecting memory leaks.
Let’s say we have the following in the CFoo class implementation:

Neither in CFoo’s destructor, nor in any other place, the delete operator is called for freeing m_buffer.
After running then closing the application in debug mode, we can see in Output/Debug window:

It shows that we have memory leaks and some additional info but not the cause.
To find out the source code which generates memory leaks, we simply have to use DEBUG_NEW MFC macro.

Now, we can get the following in Output/Debug:

Additional info were been added: the source file (c:\Projects\Test\Foo.cpp) and the line number which gnerates memory leaks. Moreover, if double-click in “Debug” window, the Visual Studio IDE jumps exactly in that source file at that line number.

Notes

  • This topic describes the detection of memory leaks generated when using the new operator, and not caused by CRT functions (malloc, calloc, etc) or WinAPI functions (LocalAlloc, GlobalAlloc, and so on).
  • MFC ClassWizard automatically adds DEBUG_NEW but not always. For that reason it is recommended to check if all MFC impementation files (.cpp) have on top the following lines:
  • Generally, for detecting memory leaks in MFC applications, all described above is enough. However, in more difficult situations which require dynamic cheching of memory allocation, MFCoffers CMemoryState class.

 

Resources

See also

2 thoughts on “How to detect memory leaks in MFC?

  1. vaibhav mathur

    HI Ovidiu

    #ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    yeah this a way by which we could detect the memory leaks.
    however i use a _crtdumpmemoryleaks() function,
    so just want to know which is more reliable and powerful for detecting memoryleaks.
    your valuable comments would lit some light in my knowledge.
    thanks
    vaibhav mathur
    vaibhavbvcoe@gmail.com

    Reply
    1. Ovidiu Cucu Post author

      Can be sure that MFC framework uses _CrtDumpMemoryLeaks itself.
      Generally, somehing already made in a well tested framework is more reliable than something else which is reinventing the wheel.

      Reply

Leave a Reply