CRT检测
定位内存泄漏位置
#include "stdafx.h" #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__) //重新定义new用于内存泄漏检测时输出行号 #define DEBUG_MALLOC(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)//重新定义malloc用于内存泄漏检测时输出行号 #else #define DEBUG_NEW #define DEBUG_MALLOC(s) #endif //这句定义不起作用,真神奇,不解,这句本身的作用也是定义#define DEBUG_MALLOC(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__),既然不起作用就自己重新定义了 //#define _CRTDBG_MAP_ALLOC #include "crtdbg.h"//这个要在DEBUG_NEW 和 DEBUG_MALLOC(s)后面调用,否则不起作用 #include <iostream> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #define malloc(s) DEBUG_MALLOC(s) #endif int _tmain(int argc, _TCHAR* argv[]) { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );//在程序退出后检查内存泄漏(程序可能会在多个位置退出,这句适用与在各种情况的退出) char *p1=new char; char *p2 = (char*)malloc(sizeof(char) * 5); //_CrtDumpMemoryLeaks();//检测当前内存泄漏,一般写在程序退出之前,但如果析构函数中有delete,本来已经正常释放的内存还会被查出内存泄漏,因为这个函数检查的是当前位置的内存泄漏 return 0; }
结果
定位调用(内存泄漏函数)位置
设置内存状态快照,用于程序代码分段寻找内存泄漏位置。
#include "stdafx.h" #ifdef _DEBUG //重新定义new用于内存泄漏检测时输出行号 #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__) //重新定义malloc用于内存泄漏检测时输出行号 #define DEBUG_MALLOC(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__) #else #define DEBUG_NEW #define DEBUG_MALLOC(s) #endif //这句定义不起作用,真神奇,不解,这句本身的作用也是定义#define DEBUG_MALLOC(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__),既然不起作用就自己重新定义了 //#define _CRTDBG_MAP_ALLOC //这个要在DEBUG_NEW 和 DEBUG_MALLOC(s)后面调用,否则不起作用 #include "crtdbg.h" #include <iostream> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #define malloc(s) DEBUG_MALLOC(s) #endif _CrtMemState s1, s2, s3; void mleak() { int * p3 = new int; } int _tmain(int argc, _TCHAR* argv[]) { //在程序退出后检查内存泄漏(程序可能会在多个位置退出,这句适用与在各种情况的退出) _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); char *p1=new char; char *p2 = (char*)malloc(sizeof(char) * 5); _CrtMemCheckpoint( &s1 ); mleak(); _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2) ) _CrtMemDumpStatistics( &s3 ); //检测当前内存泄漏,一般写在程序退出之前,但如果析构函数中有delete,本来已经正常释放的内存还会被查出内存泄漏,因为这个函数检查的是当前位置的内存泄漏 //_CrtDumpMemoryLeaks(); return 0; }
参考:
CRT
浅谈C++中内存泄漏的检测 http://tech.e800.com.cn/articles/2009/1030/1256866753344_1.html
检测内存泄漏的方法 http://blog.csdn.net/fengrx/article/details/4097185
C/C++内存泄漏及检测 http://www.cnblogs.com/skynet/archive/2011/02/20/1959162.html
Finding Memory Leaks Using the CRT Library http://msdn.microsoft.com/en-us/library/x98tx3cf.aspx