Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Application Verifier to find memory leaks

I want to find memory leaks in my application using standard utilities. Previously I used my own memory allocator, but other people (yes, you AlienFluid) suggested to use Microsoft's Application Verifier, but I can't seem to get it to report my leaks. I have the following simple application:

#include <iostream>
#include <conio.h>

class X
   {
   public:
      X::X() : m_value(123) {}
   private:
      int m_value;
   };

void main()
{
X *p1 = 0;
X *p2 = 0;
X *p3 = 0;

p1 = new X();
p2 = new X();
p3 = new X();
delete p1;
delete p3;
}

This test clearly contains a memory leak: p2 is new'd but not deleted.

I build the executable using the following command lines:

cl /c /EHsc /Zi /Od /MDd test.cpp
link /debug test.obj

I downloaded Application Verifier (4.0.0665) and enabled all checks.

If I now run my test application I can see a log of it in Application Verifier, but I don't see the memory leak.

Questions:

  • Why doesn't Application Verifier report a leak?
  • Or isn't Application Verifier really intended to find leaks?
  • If it isn't which other tools are available to clearly report leaks at the end of the application (i.e. not by taking regular snapshots and comparing them since this is not possible in an application taking 1GB or more), including the call stack of the place of allocation (so not the simple leak reporting at the end of the CRT)

If I don't find a decent utility, I still have to rely on my own memory manager (which does it perfectly).

like image 756
Patrick Avatar asked Jun 02 '10 07:06

Patrick


2 Answers

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.

like image 199
Alex F Avatar answered Sep 17 '22 21:09

Alex F


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

like image 22
Wanderley Caloni Avatar answered Sep 20 '22 21:09

Wanderley Caloni