A follow-up question to Memory leaks when calling ITK from Visual Studio DLL
I refined the problem to the simplest example.
struct A
{
public:
A()
{
mp_data = new int(0x42);
}
~A()
{
delete mp_data;
}
int* mp_data;
};
A a;
When such a global class is defined in a DLL, Visual Studio debug CRT reports that mp_data is leaked on application shutdown. Does anybody know a workaround except disabling leak reporting?
If you are calling _CrtDumpMemoryLeaks()
at the end of the main function the behaviour is expected, since mp_data
will be deleted after _CrtDumpMemoryLeaks()
was called.
You would need to call _CrtDumpMemoryLeaks()
after the last destructor of you static objects has been called (or rather in the last destructor after the memory has been freed) if you don't want to see these leaks (quite a difficult task, I wouldn't try it).
The cleaner approach is to allocate all your static objects on the heap instead (at the beginning of main
), and de-allocate them at the end of main
, and then you can call _CrtDumpMemoryLeaks()
and won't see any memory leaks.
FYI static objects with constructors and destructors are considered bad anyways, because the order in which they are constructed/destructed is not deterministic, and because of that static objects often introduce bugs which can't be debugged easily.
Edit regarding Andrey's comment:
You could try to deactivate the automatic call to _CrtDumpMemoryLeaks
by calling _CrtSetDbgFlag to unset the _CRTDBG_LEAK_CHECK_DF
flag. If that works, you can add a static object which calls _CrtDumpMemoryLeaks()
in its destructor. To make sure that this object is destructed last, you can use the #pragma init_seg(compiler) directive.
No clue if this will work... Other than that, all other solutions will most likely require you to modify the ITK library (which should be possible, it's an open source library after all?!).