最近在学习VC中MS CRT对内存泄漏的处理。自己总结了一下,写了一小段对new、malloc、realloc检测的代码:
#include "stdafx.h"
#include <Windows.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#define malloc(x) _malloc_dbg( x, _NORMAL_BLOCK, __FILE__, __LINE__)
#define realloc(x, y) _realloc_dbg( x, y, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
class A
{
public:
A() { a1 = new int; a2 = (char*)malloc(12);}
~A() { /*delete a1; free(a2);*/ }
int *a1;
char *a2;
};
int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
int* p = new int;
//delete p;
char * y = (char*)malloc(10);
//free(y);
char * x = (char*)malloc(5);
x[0] = 'm';
//free(x);
realloc( x, 100);
A a;
A * ap = new A();
return 0;
}
输出结果如下:
Detected memory leaks!
Dumping objects ->
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(25) : {100} normal block at 0x00394BB8, 12 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(25) : {99} client block at 0x00394B78, subtype 0, 4 bytes long.
Data: < > CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(44) : {98} client block at 0x00394B30, subtype 0, 8 bytes long.
Data: <xK9 K9 > 78 4B 39 00 B8 4B 39 00
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(25) : {97} normal block at 0x00397FE0, 12 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(25) : {96} client block at 0x00397FA0, subtype 0, 4 bytes long.
Data: < > CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(42) : {95} normal block at 0x00397F00, 100 bytes long.
Data: <m > 6D CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(37) : {93} normal block at 0x00397EB8, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
g:/windows核心编程代码/testmemoryleak/testmemoryleak1/testmemoryleak1.cpp(35) : {92} client block at 0x00397E78, subtype 0, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.
上面的结果可以在DebugView中查看!或是按F10(F5)到
mainret = wmain(argc, argv, envp);
#else /* WPRFLAG */
__initenv = envp;
mainret = main(argc, argv, envp);
#endif /* WPRFLAG */
#endif /* _WINMAIN_ */
/*
* Note that if the exe is managed app, we don't really need to
* call exit or _c_exit. .cctor should be able to take care of
* this.
*/
if ( !managedapp )
exit(mainret);
时,也可以在输出窗口看到。