1. Enable Memory leak detection
#define _crtdbg_map_alloc
#include <stdlib.h>
#include <crtdbg.h>
NOTE 1: The statement order cannot be modified;
NOTE 2: Valid only for debug versions
Note 3: #define语句可以去掉, but leak dump will lose detail information such as: Leaked code files and line numbers
2. Print Leak Memory report
You can see the memory leak report in the appropriate place by calling the following statement:
_CrtDumpMemoryLeaks ();
3. If the application has multiple exits, you can automatically print the memory leak information when the program exits by setting the debug flag instead of manually adding it at each exit:
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df);
4. By default, the Output window of the debug panel of VS is reported, and the behavior can be modified by the following API:
_CrtSetReportMode (_crt_error, _crtdbg_mode_debug);
CRT Memory Leak report interpretation:
If a _CRTDBG_MAP_ALLOC macro is defined, this is the report:
Detected memory leaks!
Dumping objects
C:\PROGRAM files\visual Studio\myprojects\leaktest\leaktest.cpp (20): {18}
Normal block at 0x00780e80, bytes long.
Data: < > CD CD CD CD CD CD CD CD CDs CD CD
Object dump complete.
If there is no definition, this is the case:
Detected memory leaks!
Dumping objects
{The normal block at 0x00780e80, bytes long.
Data: < > CD CD CD CD CD CD CD CD CDs CD CD
Object dump complete.
Interpretation:
Memory block number, here is 18;
Memory block type: here is normal;
Leaked memory address: here is 0x00780e80;
The size of the leaked memory block, here is 64bytes;
The hexadecimal value of the first 16byte of the leaked memory;
There are 5 types of CRT memory:
Normal: The application's own block of memory
Client:mfc Object-specific types
CRT:CRT memory blocks used by itself
Free: Already released (will not appear in the report)
Ignore: Application displays a block of memory that is marked for exclusion in memory leak reporting
The CRT implements memory leak monitoring by overwriting new and malloc:
#ifdef _DEBUG
#ifndef dbg_new
#define Dbg_new NEW (_normal_block, __file__, __line__)
#define NEW Dbg_new
#endif
#endif//_DEBUG
Set the memory opening breakpoint:
1. Modify the CRT global variables in the Watch window: _crtbreakalloc,
If you use the/MD compile option, add the context operator: {,, Ucrtbased.dll}_crtbreakalloc, if you use the/MD compilation option, add the context operator:
2. Set _CrtSetBreakAlloc (XX) through the CRT API;
To manually compare Memory:
Typical usage:
_CrtMemState S1;
_CrtMemCheckpoint (&S1);
Memory allocations take place
_CrtMemState S2;
_CrtMemCheckpoint (&S2);
_CrtMemState S3;
if (_CrtMemDifference (&S3, &S1, &S2))
_CrtMemDumpStatistics (&S3);
Using the CRT to locate memory leaks