C++内存检测

来源:互联网 发布:股票交易算法 编辑:程序博客网 时间:2024/06/11 02:03

记录下来,方便自己下次使用

#ifndef MEMORY_DETECT_H_#define MEMORY_DETECT_H_#ifdef _DEBUG// 添加头文件#define _CRTDBG_MAP_ALLOC#include <stdlib.h>#include <crtdbg.h>// 定义内存快照变量_CrtMemState sStart, sEnd, sComapre;#endif   // endif _DEBUG// 设置内存泄漏重定向到输出窗口void SetCrtReportMode(){#ifdef _DEBUG_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);#endif}void SnapShootStartMemory(){#ifdef _DEBUG_CrtMemCheckpoint(&sStart);#endif}void SnapShootEndMemory(){#ifdef _DEBUG_CrtMemCheckpoint(&sEnd);#endif}/*** 备注说明:* .普通块:(normal block)由自己的程序分配内存* .客户块:(client block)是一种特殊的内存块,它是由MFC使用的一个对象,程序退出时,该对象的析构函数没有被调用。MFC new操作符可以用来创建普通块和客户块。* .CRT块:(CRT block)是由C RunTime Library供自己使用而分配的内存块。CRT库自己来管理这些内存的分配与释放,通常你不会在内存泄漏报告中发现有CRT内存泄漏,除非程序发生了严重的错误(例如CRT库崩溃)。* .空闲块:(free block)已经被释放(free)的内存块.(不会出现在内存报告中)* .忽略块:(ignore block)程序员显示声明过不要在内存泄漏报告中出现的内存块.(不会出现在内存报告中)*/void CompareMemorySnapShoot(){#ifdef _DEBUGif (_CrtMemDifference(&sComapre, &sStart, &sEnd))_CrtMemDumpStatistics(&sComapre);#endif}// 检测内存泄漏起始点void StartMemoryDetect(){#ifdef _DEBUGSetCrtReportMode();SnapShootStartMemory();// 起始快照#endif}// 检测内存泄漏结束点void EndMemoryDetect(){#ifdef _DEBUGSnapShootEndMemory();// 结束快照CompareMemorySnapShoot();// 比较前后快照内存#endif}//_CrtDumpMemoryLeaks();#endif // endig MEMORY_DETECT_H_

使用方法

#include "MemoryDetect.h"int _tmain(int argc, _TCHAR* argv[]){StartMemoryDetect();int *p = new int;delete p;p = NULL;int *x = (int*)malloc(sizeof(int)*6);free(x);EndMemoryDetect();return 0;}