Tracing memory leaks in C++ [Microsoft-specific]
Posted by Peter | Filed under Programming
I was working on “Project Sparrow” a whole lot over this past weekend, and somehow (I forget exactly how) I ran across the ability to track memory leaks down to the exact line of source code when you’re developing with Microsoft Visual Studio. (I was using VS 2005 Express Edition)…
The very first thing you need to do is tell the compiler that you want to track memory allocations, and then include the standard headers and the CRT debugging headers. These 3 lines accomplish this:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
To be of really effective use, those lines need to be included in *every* file, which can be a bit of a pain. As such, it’s actually easier to create dedicated header file (I called mine “debug.h”) and do not add it to your VS solution. Rather, just let it sit idly by in the root folder of your project, and use the project properties to force the pre-processor to automatically include it in every file.
(Go to Project Properties, select the “Debug” configuration, then go to “Configuration Properties” -> “C/C++” -> “Advanced”. In the “Force Includes” line on the right, add the relative path to the header files. My “debug.h” file sits in the folder where the VS *.sln file is, so I used a handy built-in macro to define the path, like this:
$(SolutionDir)\debug.h
We’re not done yet! Move on to the next page to find out how to output the data!
