//The #include statements must be in the order shown here. If you change the order, the functions you use may not //work properly.
With _CRTDBG_MAP_ALLOC defined, the display shows:
-
The memory allocation number (inside the curly braces).
-
The block type, which is normal, client, or CRT.
-
The memory location in hexadecimal form.
-
The size of the block in bytes.
-
The contents of the first 16 bytes, also in hexadecimal form.
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
int _tmain(int argc, _TCHAR* argv[])
{
// dump memory leak information
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
char * a = (char*)malloc(5);
char *e = new char[10];
return 0;
}
//Result
Detected memory leaks!
Dumping objects ->
e:/vsproject/unittest/unittest.cpp(42) : {187} normal block at 0x0003D538, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
e:/vsproject/unittest/unittest.cpp(41) : {186} normal block at 0x0003D4F0, 5 bytes long.
Data: < > CD CD CD CD CD
Object dump complete.
By default, _CrtDumpMemoryLeaks dumps memory leak information to the Debug pane of the Output window, as described previously. You can reset this to dump to another location using _CrtSetReportMode
PS:
Valgrind
Valgrind是一个GPL的软件,用于Linux(For x86, amd64 and ppc32)程序的内存调试和代码剖析。你可以在它的环境中运行你的程序来监视内存的使用情况,比如C 语言中的malloc和free或者 C++中的new和 delete。使用Valgrind的工具包,你可以自动的检测许多内存管理和线程的bug,避免花费太多的时间在bug寻找上,使得你的程序更加稳固。