在VC中检测内存泄漏

声明:checkleaks.h和checkleaks.cpp这两个文件中的代码是在网上COPY的,但原来那个网站现在却找不到了

所以,这篇文章不算完全原创,呵呵。

就当作是一个存档吧


先上代码:

//checkleaks.h
#ifndef SET_DEBUG_NEW_H  
#define SET_DEBUG_NEW_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  

#pragma once  

#if defined(WIN32)  
void setFilterDebugHook(void);  
#endif 

#endif  


//checkleaks.cpp
#if defined(WIN32)  

#include <string.h>  
#include "crtdbg.h"  

#define FALSE   0  
#define TRUE    1  

_CRT_REPORT_HOOK prevHook;  

int reportingHook(int reportType, char* userMessage, int* retVal)  
{  
	// This function is called several times for each memory leak.  
	// Each time a part of the error message is supplied.  
	// This holds number of subsequent detail messages after  
	// a leak was reported  
	const int numFollowupDebugMsgParts = 2;  
	static bool ignoreMessage = false;  
	static int debugMsgPartsCount = 0;  

	// check if the memory leak reporting starts  
	if ((strncmp(userMessage,"Detected memory leaks!/n", 10) == 0)  
		|| ignoreMessage)  
	{  
		// check if the memory leak reporting ends  
		if (strncmp(userMessage,"Object dump complete./n", 10) == 0)  
		{  
			_CrtSetReportHook(prevHook);  
			ignoreMessage = false;  
		} else  
			ignoreMessage = true;  

		// something from our own code?  
		if(strstr(userMessage, ".cpp") == NULL)  
		{  
			if(debugMsgPartsCount++ < numFollowupDebugMsgParts)  
				// give it back to _CrtDbgReport() to be printed to the console  
				return FALSE;  
			else  
				return TRUE;  // ignore it  
		} else  
		{  
			debugMsgPartsCount = 0;  
			// give it back to _CrtDbgReport() to be printed to the console  
			return FALSE;  
		}  
	} else  
		// give it back to _CrtDbgReport() to be printed to the console  
		return FALSE;  
};  

void setFilterDebugHook(void)  
{  
	//change the report function to only report memory leaks from program code  
	prevHook = _CrtSetReportHook(reportingHook);  
}  

#endif   


//main.cpp
#include <windows.h>
#include <stdio.h>
#include "checkleaks.h"

int main()
{
	//一定要加上这句,而且要在DEBUG模式下才会有报告输出
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );  
	int *arr;
	arr = new int;
	return 0;
}

程序输出:

Detected memory leaks!
Dumping objects ->
e:\vs2008\try\ctemp\ctemp\main.cpp(9) : {62} client block at 0x00503DE8, subtype 0, 4 bytes long.
 Data: <    > CD CD CD CD 
Object dump complete.
The program '[3348] ctemp.exe: Native' has exited with code 0 (0x0).


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值