首页 > 其他 > 详细

VS2010检查内存泄露

时间:2015-08-21 13:32:47      阅读:249      评论:0      收藏:0      [点我收藏+]

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处)。

版权声明:本文为博主原创文章,未经博主允许不得转载。

VS2010检查内存泄露

原文:http://blog.csdn.net/yiranant/article/details/47832285

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!