Detecting Memory Leaks in Mfc Application

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?

8

2 Answers

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.

9

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.