Two sentences.
First, what is created before main (or the equivalent) begins to be destroyed after main completed. Calling _CrtDumpMemoryLeaks at the end of main may give you false positives. (Or are they false negatives?) Global object destructors are not running yet, and atexit callbacks are not running yet, so the leak output will include distributions that have not yet been properly released.
(I suspect that is why your global objects seem to be leaking. There is nothing wrong with the code, and it is indeed possible that it will clear correctly - the cleanup code still starts when _CrtDumpMemoryLeaks is called.)
Instead, you need to direct the runtime library to call _CrtDumpMemoryLeaks for you, after all, after all atexit callbacks and global object destructors have completed. Then you will see only real leaks. This snippet will do the trick. Insert at the beginning of main :
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF);
Secondly, if the above reveals true leaks from material that runs before main , you can cheat a little to make your own code a bit before anything else peeks inside. Then you can set _crtBreakAlloc before any distribution happens. Just enter the following code into your own .cpp file:
#include <crtdbg.h> #ifdef _DEBUG #pragma warning(disable:4074)//initializers put in compiler reserved initialization area #pragma init_seg(compiler)//global objects in this file get constructed very early on struct CrtBreakAllocSetter { CrtBreakAllocSetter() { _crtBreakAlloc=<allocation number of interest>; } }; CrtBreakAllocSetter g_crtBreakAllocSetter; #endif//_DEBUG
(I suspect that the code in the compiler initialization segment can be run before stdin and stdout , etc., is initialized and, of course, before any global objects are created, so it may be difficult for you to do something more complex, the higher!)
(Which costs little, I believe that these days, and for some time now this distribution before the start of main almost always bad. It makes it difficult to clean up after myself, and itโs difficult to track what is happening. Itโs certainly convenient, but you always seem to end up paying for it later. This advice, which is a lot easier to hand out than to implement, however, especially as part of a larger team.)