I am writing a wrapper class to call _CrtDumpMemoryLeaks() in WPF application. I am loading a C language DLL in the WPF application and would like to see if the there are any memory leaks in the DLL as WPF is acting as a test app for DLL also.
class MemLeak
{
static int _CRTDBG_ALLOC_MEM_DF = 0x01;
static int _CRTDBG_LEAK_CHECK_DF = 0x20;
static int _CRTDBG_MODE_DEBUG = 0x2;
static int _CRTDBG_MODE_WNDW = 0x4;
static int _CRT_WARN = 0;
static int _CRT_ERROR = 1;
static int _CRT_ASSERT = 2;
[DllImportAttribute("msvcrtd.dll", EntryPoint = "_CrtDumpMemoryLeaks", SetLastError = true)]
static extern int _CrtDumpMemoryLeaks();
[DllImportAttribute("msvcrtd.DLL", EntryPoint = "_CrtSetDbgFlag")]
static extern int _CrtSetDbgFlag(int newFlag);
[DllImportAttribute("msvcrtd.DLL", EntryPoint = "_CrtSetReportMode")]
static extern int _CrtSetReportMode(int reportType, int reportMode);
public static void StartMemLeakLogging()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_C开发者_JAVA技巧RT_ERROR | _CRT_WARN | _CRT_ASSERT, _CRTDBG_MODE_DEBUG);
}
public static void StopMemLeakLogging()
{
_CrtSetReportMode(_CRT_ERROR | _CRT_WARN | _CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW);
int i = _CrtDumpMemoryLeaks();
}
}
I am using Visual Studio 2008 SP1 on Windows XP Professional SP3. Strangely I had to download the msvcrtd.dll file because the system could not find it. After that, just copied it to the debug folder and the application started working. However, I don't see the memory leak information in the output window during the debugging even if I intentionally allocated memory and not free in the DLL code.
Also, I cannot change the source code of the DLL else would have tried putting these functions in the DLL source code. I tried creating a MFC application and calling DLL functions, the MFC application detects the memory leaks and displays in the output window even if I dont call the _CrtDumpMemoryLeaks() because I think MFC in debug might internally be calling this function but it doesnt work with WPF test app.
Got it working. The link below for reference
http://social.msdn.microsoft.com/Forums/en/clr/thread/484de950-f488-452e-a9bf-b8b4cd2d1f75
精彩评论