Q: Which is the simplest method for detecting memory leaks in MFC code?
A: Detecting memory leaks in MFC code is pretty simple because the MFC framework has bult-in support for that purpose.
Let’s take a short example:
Also presume that delete operator is never called for freeing m_buffer.Code:#include "StdAfx.h" #include "Foo.h" CFoo::CFoo() { m_buffer = new char[128]; strcpy(m_buffer, "Baba Safta"); } CFoo::~CFoo() { }
After running then closing the program in debug mode, we can see in Debug window:
It shows that we have memory leaks and some additional info but it doesn't tell us the cause.Code:Detected memory leaks! Dumping objects -> {183} normal block at 0x0036B320, 128 bytes long. Data: 42 61 62 61 20 53 61 66 74 61 00 CD CD CD CD CD Object dump complete. The program '[1758] MyTest.exe: Native' has exited with code 0 (0x0).
To find out the source code which generates memory leaks, we simply have to use DEBUG_NEW MFC macro.
Now, the Debug window looks a little bit different:Code:#include "StdAfx.h" #include "Foo.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CFoo::CFoo() { m_buffer = new char[128]; // <-- double click in "Debug" window to go here! strcpy(m_buffer, "Baba Safta"); } CFoo::~CFoo() { // <-- should free the buffer to avoid memory leaks! }
Additional info were been added: the source file (c:\Projects\Test\Foo.cpp) and the line number which gnerates memory leaks (10). Moreover, if double-click in Debug window, the Visual Studio IDE jumps exactly in that source file at that line number.Code:Detected memory leaks! Dumping objects -> c:\Projects\Test\Foo.cpp(10) : {183} normal block at 0x0036B320, 128 bytes long. Data:42 61 62 61 20 53 61 66 74 61 00 CD CD CD CD CD Object dump complete. The program '[3950] Test.exe: Native' has exited with code 0 (0x0).
Resources:
See also:


Reply With Quote
