Monday, October 28, 2013

Finding Memory Leaks Using the CRT Library

Memory leaks, defined as the failure to correctly deallocate memory that was previously allocated, are among the most subtle and hard-to-detect bugs in C/C++ applications. A small memory leak might not be noticed at first, but over time, a progressive memory leak can cause symptoms that range from decreased performance to crashing when the application runs out of memory. Worse, a leaking application that uses up all available memory can cause another application to crash, creating confusion as to which application is responsible. Even seemingly harmless memory leaks might be symptomatic of other problems that should be corrected.
The Visual Studio debugger and C Run-Time (CRT) libraries provide you with the means for detecting and identifying memory leaks.

Enabling Memory Leak Detection

The primary tools for detecting memory leaks are the debugger and the C Run-Time Libraries (CRT) debug heap functions.

To enable the debug heap functions, include the following statements in your program:

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

For the CRT functions to work correctly, the #include statements must follow the order shown here.

Including crtdbg.h maps the malloc and the free functions to their debug versions, _malloc_dbg and free, which track memory allocation and deallocation. This mapping occurs only in debug builds, which have _DEBUG. Release builds use the ordinary malloc and free functions.

The #define statement maps a base version of the CRT heap functions to the corresponding debug version. If you omit the #define statement, the memory leak dump will be less detailed.
After you have enabled the debug heap functions by using these statements, you can place a call to _CrtDumpMemoryLeaks before an application exit point to display a memory-leak report when your application exits:

_CrtDumpMemoryLeaks();

If your application has multiple exits, you do not need to manually place a call to _CrtDumpMemoryLeaks at every exit point. A call to _CrtSetDbgFlag at the beginning of your application will cause an automatic call to _CrtDumpMemoryLeaks at each exit point. You must set the two bit fields shown here:

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

By default, _CrtDumpMemoryLeaks outputs the memory-leak report to the Debug pane of the Output window. You can use _CrtSetReportMode to redirect the report to another location.
If you use a library, the library might reset the output to another location. In that case, you can set the output location back to the Output window, as shown here:

_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );

Interpreting the Memory-Leak Report

If your application does not define _CRTDBG_MAP_ALLOC, _CrtDumpMemoryLeaks displays a memory-leak report that looks like this:

Read more: MSDN
QR: Inline image 1