Memory Leak Checking in Visual C++
The Microsoft Visual C++ compiler comes with routines that can be used to check for memory leaks, i.e. instances
where one has dynamically allocated memory using the new or malloc command and not de-allocated it
using a corresponding delete or free command. One can find samples of the routine use in the Microsoft
Help system under
Visual C++ Programmers Guide | Runtime Library Reference | Debug Function Reference | _CrtDumpMemoryLeaks
To make it a bit easier to use these routines, I've created a header (LeakCheck.h)
and source file (LeakCheck.cpp) that contain the requisite code to check for memory
leaks in Win 32 console applications. To use these routines, one merely includes the LeakCheck.h file in
ones source, and then executes the initLeakCheck()
function in the main()
routine. If
there are memory leaks, then this fact is output to the console when the program terminates. The following is a
sample test program (LeakCheckTest.cpp) and output that demonstrates the use of
these routines.
// //############################################################################## // LeakCheckTest.cpp //############################################################################## // // LeakCheckTest : Demonstrates the use of Visual C++ Memory Leak // detection routines. // //############################################################################## // //############################################################################## // #include "LeakCheck.h" int main() { // // Initialize leak checking code // initLeakCheck(); // // allocate an array, and don't delete it before the program ends. // double* x = new double[10]; return 0; }
Output generated :
Chris Anderson May 27, 1999