How to use Application Verifier to find memory leaks

CRT memory leaks detection (without stack trace):

// debug_new.h
#pragma once

#include "crtdbg.h"

#ifdef _DEBUG
#ifndef DEBUG_NEW
#define DEBUG_NEW   new( _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif

All .cpp files:

#include "debug_new.h"

...

// After all other include lines:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

...

Write this once in the program initialization code:

_CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

In MFC, all this is already implemented in MFC headers. You only need to ensure, that every cpp file contains these lines:

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

Restrictions: this catches only "new" memory leaks, all leaks, caused by another functions, like malloc, are not caught.

Don't make any allocations inside of .h files - they will be printed without source lines, because DEBUG_NEW is defined after all #include lines.


Application Verifier only catches leaks in DLLs. Try to read the tooltip in the leak checkbox. That's what it says.


I have a feeling that Application Verifier special cases the exit path and doesn't flag these as leaks - after all, the entire process heap is free on process exit.

Try writing another sample where you initialize the same pointer again - basically lose the reference to the previous allocation. That should certainly be flagged. Let me know the results.

Also, AppVerifier (if you have all the options enabled) should also catch buffer overflows, underflows, writing to stack locations marked RO etc.


Memory Validator from Software Verification will catch memory leaks, and show the complete callstack from the leak's allocation. While it is a commercial product, it has a trial period so programmers can try it and see if it is worth the price to them.