标签:
VS2010中的C++程序内存泄露检测
对于MFC程序是支持内存检测的。对于非MFC程序而言,CRT有一套内存泄露的函数,最常用的是 _CrtDumpMemoryLeaks();如下所示:
#include <crtdbg.h>
int main() {
int *pInt = new int();
char *pChar = new char();
double *pDouble = new double();
// position 1
_CrtDumpMemoryLeaks();
return 0;
} 运行之后,结果如图1所示:可以看到,在第71,72,73次({71}{72}{73})分配内存时发生了泄露,略有不足的是,没有显示出是哪一行导致的内存泄露。将#include <crtdbg.h>(<crtdgb.h>必须被包含)改为如下:
#ifdef _DEBUG #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__) #else #define DEBUG_CLIENTBLOCK #endif #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #ifdef _DEBUG #define new DEBUG_CLIENTBLOCK #endif运行之后,结果如图2所示:
可以看到是因为main.cpp的第16行导致了4 bytes的内存泄露,第17行...
但是这段代码仍然存在一些问题,例如_CrtDumpMemoryLeaks()放在position 1时,虽然接下来使用delete释放new分配的内存,但是运行后结果与图2仍然相同。如下所示:
int main() {
int *pInt = new int();
char *pChar = new char();
double *pDouble = new double();
// position 1
_CrtDumpMemoryLeaks();
delete pInt;
delete pChar;
delete pDouble;
//position 2
// _CrtDumpMemoryLeaks();
return 0;
} 最好的办法是将_CrtDumpMemoryLeaks()放置在函数的出口处(如position 2处)。版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yiranant/article/details/47832285