views:

761

answers:

3

Hello,

I would like to get the memory leaks information using _CRTDBG_MAP_ALLOC, and especially the files and line numbers, but I don't get them at the end. I only get something like this:

{130} normal block at 0x00695128, 16 bytes long. Data: <\ E Pi > 5C A5 45 01 02 00 00 00 01 00 00 00 E8 50 69 00

I've seen that this should be before all the includes:

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

And some people recommend to add this after all the includes in all the sources files:

#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

HOWEVER, in the main.cpp, if I explicitly add a memory leak, it appears with the line number in my output! So it works, but not for everything...

As I use the Boost librairies, I suspect that the memory leaks all happen somewhere in these... (shared_ptr ?). But how to know where these memory leaks come from then?

+2  A: 

Try using _CrtSetAllocHook which registers callback functions before each heap allocation. A GUI app that uses this to highlight the line of the allocation that leaked can be found here: Visual Leak Detector

Phillip Ngan
+3  A: 

Generally _CRTDBG_MAP_ALLOC is not going to help you with 3rd party code. _CRTDBG_MAP_ALLOC redirects the normal memory allocation functions (i.e. malloc) to special debug versions that take the file and line number (i.e. _malloc___dbg) at compile time. If the 3rd party code wasn't built with _CRTDBG_MAP_ALLOC defined, then you're not going to see that information. Also, this doesn't help you with the non-CRT memory allocation functions (i.e. HeapAlloc, GlobalAlloc, LocalAlloc, VirtualAlloc, etc), though boost almost certainly uses the CRT functions.

If the allocation number is consistent, you could use _CrtSetBreakAlloc to set a breakpoint when that allocation occurs to see what code is allocating the memory. Also, keep in mind that if you are calling _CrtDumpMemoryLeaks at the end of your program then any global objects have not been destructed yet and their memory will show up in the output.

Luke
True, probably Boost use many globals and that's why I have all these "memory leaks".Using CrtSetBreakAlloc doesn't seem to work, it never breaks. Probably because the memory allocation occurs in the Boost libraries?
TigrouMeow
A: 

I would think that\ _CRTDBG_MAP_ALLOC should work with header-only libraries in boost (e.g. shared_ptr) as they are implented in the headers. I highly doubt that you will find any memoryleaks inside shared_ptr though. I even doubt that shared_ptr even calls allocates heap memory. Remember, this is extremely well tested code and chances are that you're the one that is causing the leak.

As there is no good indication on where the leak occurs I would guess that it is caused by a memory-allocation in a third party library and that the library expects you to do the cleanup.

larsm