In the MFC development environment, when the run exits, Visual Studio prompts for a memory leak in the Output window. You can also use MFC class CMemoryState to dynamically detect and output memory leak information.
In non-MFC frameworks, these functions need to be implemented with CRT functions.
1. Calling the _CrtDumpMemoryLeaks () function outputs the current memory leak in the Output window. If you add at the beginning of the program: _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
statement, the CRT automatically calls the _CrtDumpMemoryLeaks function at each exit of the program, so that when the program terminates, all memory leaks are displayed in the Output window.
2. Using _CrtMemState structure Sentinel monitoring of memory leaks, example:
//定义3个内存状态
_CrtMemState s1,s2,s3;
//记录开始的内存状态
_CrtMemCheckpoint( &s1 );
int *p = new int;
//记录结束时的内存状态
_CrtMemCheckpoint( &s2 );
//比较2个内存状态,并将差异保存到s3中
if( _CrtMemDifference( &s3, &s1, &s2 ) )
{
//输出内存泄漏信息
_CrtMemDumpAllObjectsSince( &s3 );
}
3. Redirect Output information. Memory leak Tip Default is output in the Output window, you can redirect its output position through _CrtSetReportMode. Example (redirect output to specified file):
CAtlFile hFile;
hFile.Create( _T("D:\\report.txt"), GENERIC_WRITE, FILE_SHARE_WRITE, CREATE_ALWAYS );
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, hFile );
You can also redirect to form hints (forms with the Terminate, continue, ignore buttons), and the assertion is to output this form. You can also intercept messages by using the _CrtSetReportHook function before outputting to a specified destination. Such as:
_CrtSetReportHook (myreportingfunction);
The definition of myreportingfunction is as follows:
int MyReportingFunction( int nReportType, char *szMsg, int *pRetVal )
{
*pRetVal = 0;
if( nReportType == _CRT_WARN )
{
AtlMessageBox( NULL, _U_STRINGorID( CA2T(szMsg)));
}
return 0;
}