Cannot use VS2008 memory leak detector

796 views Asked by At

I am trying to use VS2008 memory leak tool, but I have failed to build it at all.

The simplest scenarios works well, but when I try to use CObject - it does not compile

Here is the code (Its a newly create console application)

#include "stdafx.h"

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

#define _AFXDLL
#include "afx.h"

class DRV : public CObject {};

int _tmain(int argc, _TCHAR* argv[])
{
    DRV *d = new DRV;
}

This results : error C2059: syntax error : 'constant' in afx.h:

void* PASCAL operator new(size_t nSize);

If I try to move the #ifdef _DEBUG below the #include "afx.h", I get:

error C2661: 'CObject::operator new' : no overloaded function takes 4 arguments

on line:

DRV *d = new DRV;

So - what am I doing wrong? Can I use the build in VS2008 memory leak detector? Please help

1

There are 1 answers

7
Alex F On BEST ANSWER

Create file DebugNew.h and add this code to it:

#pragma once

#include "crtdbg.h"
#ifdef _DEBUG
#define DEBUG_NEW   new( _NORMAL_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_NEW
#endif

In cpp file:

#include "stdafx.h"
#include "DebugNew.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif    

int _tmain(int argc, _TCHAR* argv[])
{
    CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

    char *d = new char[100];
}

DebugNew.h file defines new operator, which allows to include source line information for every allocation. #define new DEBUG_NEW line redefines default new to DEBUG_NEW, only in Debug build. This line should be placed after all #include lines in all .cpp files. CrtSetDbgFlag enables memory leak allocation in debug build - when the program exits, all unreleased allocations are printed. Since new operator is redefined, they are printed with source line information.

For MFC projects, you only need to add lines

#ifdef _DEBUG
#define new DEBUG_NEW
#endif    

to every .cpp file. All other things are already done by MFC. MFC project, created by MFC application Wizard, already contains all required stuff by default. For example, create Win32 Console Application with MFC support using Wizard - memory leaks tracking is working. You only need to add new DEBUG_NEW redefinition to every new file added to the project.