0

Windows内存泄漏和溢出检测

发表者:wenzhou1219分类:接口2016-03-12 21:46:07 阅读[696]

在程序中包含头文件MemoryCheck.h,注意头文件位置必须放在MFC/ATL等库文件的前面,因为MFC、ATL、WTL等库中默认包含了crtdbg.h,由于我们显示定位行号需要开启_CRTDBG_MAP_ALLOC宏后再链接,需要将本文件在这些库文件之前包含。

如下为程序使用实例,非常简单,照着使用就行:

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{

	//初始化,开始检查,开启自动检查泄露,不自动检查溢出,不弹框提醒,日志输出到文件log.txt中
	InitMemoryCheck(true, false, false, _T("c:\\log.txt"));

	//内存泄露检查
	int* a = new int[20];
	char* b = (char*)malloc(10);
	//MemCheckLeak();

	//内存溢出检查
	a[20] = 1;
	MemCheckOverflow();
	printf("\n");

	//堆内存状态比较
	MemStateSave();
	int* c = (int*)malloc(10);
	int* d = new int[10];
	MemStateSave();
	MemStateCompareDump();
	char* e = new char[1];
	MemStateSave();
	MemStateCompareDump();

	//自定义报告输出,可做日志用
	MemReportError("错误-自定义报告输出\n");
	MemReportWarn("警告-自定义报告输出\n");
	MemReportAssert("断言-自定义报告输出\n");
	printf("\n");

	//检查完毕
	UninitMemoryCheck();
	return 0;

	/**程序结束时自动检查泄露**/
}

生成的log.txt内容如下:

HEAP CORRUPTION DETECTED: after Client block (#123) at 0x00859C90.
CRT detected that the application wrote to memory after end of heap buffer.

Memory allocated at e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10).
Client located at 0x00859C90 is 80 bytes long.

Memory allocated at e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10).
0 bytes in 0 Free Blocks.
10 bytes in 1 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
40 bytes in 1 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 50 bytes.
0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
1 bytes in 1 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 1 bytes.
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(30) : 错误-自定义报告输出
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(31) : 警告-自定义报告输出
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(32) : Assertion failed: 断言-自定义报告输出

Detected memory leaks!
Dumping objects ->
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(25) : {128} client block at 0x00859E18, subtype 0, 1 bytes long.
 Data: < > CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(22) : {127} client block at 0x00859DB0, subtype 0, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(21) : {126} normal block at 0x00859D68, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(11) : {124} normal block at 0x00859D20, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10) : {123} client block at 0x00859C90, subtype 0, 80 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

是不是很简单?


下载链接  访问密码 66d9






名字:

个人主页地址:

E-mail:

评论列表