0

I have added the following to the end of my main and I get the memory leak report but there is no break point created showing where the leak occurs in my code when I run it in debug mode. I am using VS c++ 2010 express. Is there something that I am doing wrong or something wrong with the code that I added. I can post more of the code if it would be helpful.

#ifdef _WIN32 if (_CrtDumpMemoryLeaks()) { cout << "Memory leaks!" << endl; } #endif #ifdef _DEBUG int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit _CrtSetDbgFlag(flag); _CrtSetBreakAlloc(427); #endif 
2
  • 1
    If you code is compilable on Linux, try valgrind on Linux .... Commented Jul 6, 2014 at 5:57
  • Try VLD - vld.codeplex.com Commented Jul 6, 2014 at 6:57

2 Answers 2

8
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(flag); 

This is quite enough to enable memory leaks detection. Don't call _CrtDumpMemoryLeaks directly. However, in order to get source code line, where leaked allocation was called, you need to do a bit more.

Add these lines to the beginning of every .cpp file, immediately after all #include lines:

#ifdef _DEBUG #define new DEBUG_NEW #endif 

For MFC project, this is enough, MFC headers contain DEBUG_NEW. For non-MFC projects, create file DebugNew.h:

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

Include it to every .cpp file. Memory leaks report now should look like this:

Detected memory leaks! Dumping objects -> c:\projects\test\main.cpp(20) : {181} normal block at 0x005A80F8, 100 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete. 
Sign up to request clarification or add additional context in comments.

Comments

3

http://msdn.microsoft.com/en-us/library/4wth1ha5.aspx

First I argue that these set of code you posted here needs to go very first lines of the main function body, but I'm not sure.

As far as I know, _CrtSetBreakAlloc function will let Debugger break when an application tries to allocate on the location passed as an argument.

Do you get location of the memory when debugger dumps memory leaks to output window? You will have to copy that location and use that as argument of _CrtSetBreakAlloc call on the next run.(like number 276 in the output below for example)

Dumping objects -> {276} normal block at 0x007AC200, 4 bytes long. Data: < > CD CD CD CD Object dump complete. 

Then the function call would be _CrtSetBreakAlloc(276);

Personally, I recommend you to use Visual Leak Detector, which will give you more clue about where the leak happened in the message.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.