需求
检测代码中的内存泄露情况,辅助开发人员解决bug。
目标
1. 使用尽量简单。尽量不要修改已有代码。
2. 对于malloc和new分配出现的内存泄露能够检测出来。
3. 友好的提示,报告出错的未知,定位到文件对应的行。
4. 对于泄露的内存,能够dump出部分内容。
代码
使用方法:将如下两个文件放入你的工程,如果你有的每个cpp都包含了特定的头文件,如stdafx.h,那么将leak_detector.h包含到那个头文件当中,并在之前定义宏ENABLE_LEAK_DETECT开启内存泄露检测。
//leak_detector.h
// Copyright (C) 2013.
// Author:xht
#ifndef __LEAK_DETECTOR_H__
#define __LEAK_DETECTOR_H__
#ifdef ENABLE_LEAK_DETECT // define this macro to enable leak detect
#include <stdlib.h>
#include <string>
#include <map>
#include <vector>
#pragma comment(lib, "commonlib.lib")
struct LeakFuncType{
LeakFuncType(){}
};
typedef LeakFuncType* PLeakFuncType;
void* __cdecl MallocDbg(size_t size, const char* file_name, int line_number);
void __cdecl FreeDbg(void* addr);
void* __cdecl operator new(size_t size, const char* file_name, int line_number, LeakFuncType unused);
void __cdecl operator delete(void* addr);
void* __cdecl operator new[](size_t size, const char* file_name, int line_number, LeakFuncType unused);
void __cdecl operator delete[](void* addr);
#define malloc(Size) MallocDbg((Size), __FILE__, __LINE__)
#define free(addr) FreeDbg((addr))
#define DEBUG_NEW new(__FILE__, __LINE__, LeakFuncType())
#define new DEBUG_NEW
#else
#endif
#endif // __LEAK_DETECTOR_H__
#ifdef ENABLE_LEAK_DETECT
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#endif
#include <assert.h>
#include <Windows.h>
#in