c++ – How to track down memory leaks

Question:

I work under Visual Studio. How do you know if a program has a memory leak or not?

Answer:

It is possible to detect memory leaks using the debugger and the CRT (Runtime Library) heap debug functions. They are included as follows:

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

It is important that the include / define statements follow in this order.

Including the header file <crtdbg.h> maps the malloc and free functions to their debug versions: _malloc_dbg and free . The define will make the memory leak dump more verbose (generally speaking, it maps base versions of CRT heap functions to their respective debug versions).

Next, we place a call to _CrtDumpMemoryLeaks in front of the application exit point to display a memory leak report before the application exits:

_CrtDumpMemoryLeaks();

If there are multiple exit points, there is no need to write this function call all over the place. It is enough to call the _CrtSetDbgFlag function at the beginning of the application, which will lead to an automatic call of the _CrtDumpMemoryLeaks function at each exit point. To do this, you need to set the values ​​of two bit fields:

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

By default, _CrtDumpMemoryLeaks reports the memory leak in the Debug area of ​​the Output window.

Next, see the received data, it clearly indicates the type of block, its location, the size of the leak and some other information. Blocks come in different types (see CRT help).

Note: In some cases, _CrtDumpMemoryLeaks can mistakenly diagnose a memory leak, but I will not describe these situations here, if necessary or if you don’t figure it out yourself – write comments;)

Scroll to Top