I am implementing a memory tracker in my application so that further down the line, should I get any memory leaks I can switch this little guy on to find it.
All is great except that I am never passed the filename or the line number. Is there some flag I have to set using _CrtSetDbgFlag
, or a preprocessor command?
After I ran the thing (bare-bones) it showed 26 allocations that were not cleaned up and I am pretty sure they are not me, but have no idea where they occurred.
Thanks in advance!
From the <crtdbg.h>
header file:
#ifdef _CRTDBG_MAP_ALLOC
#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
// etc...
#endif
Note how the redefinition now calls another version of malloc that has the file and line number that you are looking for. Clearly, to make this work you will have to #define _CRTDBG_MAP_ALLOC and #include crtdb.h. This is best done in your precompiled header file so that you can be reasonably sure that all of your code will be compiled with these macros in effect.
That still doesn't guarantee that you'll get this info. Your project might be using a .lib that was compiled without it. Another failure mode is DLLs that might be unloaded just before you generate the leak report. The file and line info for that DLL will be unloaded as well.
There's a fallback to diagnose those kind of trouble makers. The leak report has a line for the leak that starts with the block number, shown at the start inside curly braces. As long as that block number is stable between runs, you can force the debugger to break when the allocation is made. Put this code in your main method or whatever point in your code that executes early:
_crtBreakAlloc = 42; // Change the number