
mem leaks when using std::map in a dll
Hi,
Thanks for using Microsoft products.
This problem only happens when DLL version of the C runtime is used. There
is a difference for STL object when DLL or static version of the c-runtime
is used. For static library, since the STL is implemented as a template, it
is not instantiated until it is referenced. But for DLL version of the
C-runtime, STL objects is explicit instantiated and exported from the DLL,
the static and global objects are allocated when DLL is loaded and are
won't be released until the DLL is unloaded. The de{*filter*} generates the
memory leaks because the MFC DLL is unloaded first, at the time
_CrtDumpMemoryLeak() is called, those memory has not been freed yet which
cause the MFC to report the leak. You can not really control the unloading
sequence of DLL if you are doing implicit linking.
If you use run-time debugging functions, the correct way to detect leak to
set _CRTDBG_REPORT_FLAG so that _CrtDumpMemoryLeak is automatically called
at appropriate time. To do that, add the following lines to the code:
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
For example. This should be report memory leaks:
void ThisFunctionLeaks()
{
std::ofstream leakyStream;
Quote:
}
void main()
{
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpFlag);
const std::string leakedString = "This string Leaks";
ThisFunctionLeaks();
Quote:
}
Workaround:
1. Link the DLL with static version of the C-runtime, but that will
increase the DLL size.
2. Changing the DLL loading sequence. Put the mfc42d.lib in front of your
own DLL in the project settings | Link | Input | Object/module. It will
unload the mfc DLL after your own DLL being unloaded, so the leak will not
be reported. However, it is not very good.
Hope this information helps.
Best Regards,
Bill
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use.
?2001 Microsoft Corporation. All rights reserved.