Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 2008 (C++) memory leak detection not showing file/method location - how to get that to work?

I am using the instructions found here to try to find memory leaks in a Win32 application. As described, I put the

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

Lines at the top of a file (the cpp file that contains WINAPI _tWinMain) and then at the exit point of winmain I added

_CrtDumpMemoryLeaks();

Unfortunately I do not see the line numbers/locations for the leaks (but I do get a list of leaks).

I also tried putting

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); 
_CrtSetReportMode ( _CRT_ERROR, _CRTDBG_MODE_DEBUG); 

at the beginning of winmain - and again, no luck.

I find this odd because I usually have had no problems ever finding leaks or having them reported automatically.

This is a huge, old legacy app I am working on for a new employer. In the past I have worked from the standard VS wizard.

Any suggestions on how to get source lines/methods that are causing the leaks? (or at least the lines for the "new" calls?

EDIT:

I also tried visual leak detector - with no success.

Very strange.

EDIT

I tried using the redefinition of new as listed below, however I get errors when boost is compiled in.

like image 710
Tim Avatar asked Oct 14 '09 17:10

Tim


1 Answers

Are you sure the code that's leaking is using the CRT debug allocation routines? That requires using malloc() or new (as opposed to LocalAlloc, GlobalAlloc, some custom block allocator, etc..) and that _DEBUG (I think) must be defined when the CRT headers were included.

In order to get source lines for leaks, you will need to define DEBUG_NEW everywhere the allocations occur. This is because in order to track them, each allocation must be replaced with a call that includes __FILE__ and __LINE__. The standard definition from the wizard looks something like:

#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

This doesn't handle malloc, there's probably a similar incantation for that, if the code you're debugging uses malloc instead of new.

If you're using pre-compiled headers, you can just put this in the precompiled header file and it will affect all the source files in that project.

like image 153
Tim Sylvester Avatar answered Nov 15 '22 19:11

Tim Sylvester