How to detect memory leak when memory allocation n

2019-08-10 02:51发布

问题:

I got a memory leak (55 bytes) on my program like this. I am using C++, MFC, Visual Studio 2010.

Detected memory leaks! {13497} normal block at 0x0E44C248, 55 bytes long. Data: 44 3A 5C 46 44 41 53....

the problem is, the memory allocation number "13497" is not always same. it's always different number if I run the program again. I wanted to find where I didn't release the memory before the exit, with _crtBreakAlloc, but it seems not possible to break on a memory allocation number. I used _CrtSetDbgFlag, and _CrtDumpMemoryLeaks as well, but it also didn't work well.

Is there any way to detect the memory leak in this case?

Thank you.

回答1:

You can use a static analizer like cppcheck or, as Joe said, remap operator new.

I developed some memory leaks utilities that you can use:

https://github.com/check69/Utils/blob/master/leaks.cpp

https://github.com/check69/Utils/blob/master/leaks.h

There is some visual studio instruction to get the leaks in the console output, to debug easier.

PS: I would put this as a comment in joe post, but I need 50 points to put comments.



回答2:

Well there are a few ways to attack this.

  1. Look at the dump of the data for any sort of strings you might recognize. That might help you locate it.
  2. Put a conditional breakpoint on memory allocations that only breaks if the size requested (or being allocated) is 55 bytes.
  3. You might get better results by putting something like this really early in a header that all of your code includes (like stdafx.h)

This code remaps operator new

#ifdef _DEBUG
#    define _CRTDBG_MAP_ALLOC
#    include <crtdbg.h>
#    include <new>
#    include <memory>
#    define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#    define new DEBUG_NEW
#endif
  1. Also, does the leaked memory amount go up the more you run/use your application? If not, it might not really be a leak at all. Sometimes you can get leaks reported for statically allocated objects. In the very least, take a close look at the static allocations you make


回答3:

Hello thanks for your answers..

I found the leak location very easily by using "Visual Leak detector" from https://vld.codeplex.com/ I strongly recommend this one to those who have the same problem. :) you can just download it and put it in your project.