I'm working on an MFC Visual C++ project. As I understand from MSDN, _CrtDumpMemoryLeaks()
should return TRUE
when there are memory leaks.
After noticing it is TRUE, I tried to find the first point in the code where it becomes TRUE. Evidently, it is TRUE right from the very start. If I click F10 (step-over) to start debugging the program, and enter _CrtDumpMemoryLeaks()
in the watch window, it shows TRUE even before the first line of code, in the entry point to the program:
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine, int nCmdShow)
#pragma warning(suppress: 4985)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
Also, I speculated that maybe the debugging facilities are not initialized at that point and that the TRUE is erroneous. So I set a breakpoint at the first line in the OnInitDialog()
function and there too the value is TRUE.
How come I have memory leaks that early in the program?
You misinterpret the return value.
TRUE
doesn't mean memory leak, it means there're some unreleased blocks in the heap, that might just as well be pointed to by some pointers in the program. Those objects might be created by CRT startup code and by the static objects constructors.If you're still suspicious - set an allocation hook and inspect when objects are created. To do this early enough you'll need an object with constructed during startup - use
#pragma init_seg( compiler )
for that.C++ initializes static objects before calling main() method (or WinMain if that's the case).
Do you have static objects somewhere? Do you use Singleton to initialize some object that's never freed? Do you use some framework that could do this behind your back?
If you have things allocating memory during static initialisation (which happens before winmain is called) then these will show up as memory leaks.
You could try putting a breakpoint on HeapAlloc() - you'll probably see that gets hit before winmain does.