Mark Morrisson
Mark Morrisson

Reputation: 2703

Detecting memory leaks in MFC application

I'm writing an MFC app using Visual 2017 and when the application exits in debug mode, I get this:

Detected memory leaks! Dumping objects -> {74} normal block at 0x00000230E49A7000, 16 bytes long. Data: <0 0 > 30 00 97 E4 30 02 00 00 00 00 00 00 00 00 00 00 Object dump complete.

So, in order to know which function is causing the leak, I've added these lines in stdafx.h:

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

And these lines in CWinApp::InitInstance():

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetBreakAlloc(74);

Though, it did not work. I suspect that the 74th memory allocation number has been made before my code is executed. Which method could I overload to be certain to be called first?

Upvotes: 2

Views: 6472

Answers (2)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

Step into your app to start debugging (that's step, not run, so you'll be stopped in the debugger before anything in your program has run), then set _crtBreakAlloc to the allocation you want to stop at (74). Then run and you should get a break on the 74th allocation. CRT Debug Heap Details has information on this variable.

This Microsoft support article also lists instructions for using _crtBreakAlloc in the debugger.

Upvotes: 3

Ovidiu Cucu
Ovidiu Cucu

Reputation: 124

Writing this code

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

in top of each implementation (.CPP) file, can help you to detect the source of memory leaks. See also: How to detect memory leaks in MFC.

Upvotes: 1

Related Questions