您的位置:首页 > 编程语言 > C语言/C++

一个简单的C++内存泄漏检测程序

2017-02-06 20:40 344 查看
基本思路就是跟踪程序中的malloc和free调用,然后检测是否有漏掉的free调用,代码如下:

MemCheck.h

#ifndef __MEM_CHECK_H__
#define __MEM_CHECK_H__

#include <cstddef>

void* _Malloc_Trace_Call_(std::size_t MemSize, const char* SourceFile, int LineNumber, std::size_t Alignment = 0);
void _Free_Trace_Call_(void* Ptr, std::size_t Alignment = 0);

void DumpMemoryInfo();

#undef malloc
#define malloc(Size) _Malloc_Trace_Call_(Size, __FILE__, __LINE__)

#undef free
#define free(Ptr) _Free_Trace_Call_(Ptr)

#undef _mm_malloc
#define _mm_malloc(Size, Alignment) _Malloc_Trace_Call_(Size, __FILE__, __LINE__, Alignment)

#undef _mm_free
#define _mm_free(Ptr) _Free_Trace_Call_(Ptr, 1)

#endif


MemCheck.cpp

#include <iostream>
#include <cstdlib>
#include <map>
#include <mutex>
#include "MemCheck.h"

#undef malloc
#undef free
#undef _mm_malloc
#undef _mm_free

namespace
{
struct MemInfo
{
MemInfo(std::size_t _Size, const char* _SourceFile, int _LineNumber)
:Size(_Size)
, SourceFile(_SourceFile)
, LineNumber(_LineNumber)
{

}

std::size_t	Size;
const char*	SourceFile;
int		LineNumber;
};

std::map<void*, MemInfo> g_MemInfoMap;

std::size_t g_TotalMemAllocation = 0;
std::size_t g_TotalMemDeallocation = 0;

std::mutex g_Mutex;
}

void* _Malloc_Trace_Call_(std::size_t MemSize, const char* SourceFile, int LineNumber, std::size_t Alignment )
{
void* Ptr = nullptr;
std::lock_guard<std::mutex> Locker(g_Mutex);
if (Alignment > 0)
{
Ptr = _aligned_malloc(MemSize, Alignment);
}
else
{
Ptr = malloc(MemSize);
}

if (Ptr != nullptr)
{
g_MemInfoMap.emplace(Ptr, MemInfo(MemSize, SourceFile, LineNumber));
g_TotalMemAllocation += MemSize;
return Ptr;
}
else
{
throw std::bad_alloc();
}
}

void _Free_Trace_Call_(void* Ptr, std::size_t Alignment )
{
std::lock_guard<std::mutex> Locker(g_Mutex);
auto Iter = g_MemInfoMap.find(Ptr);
if (Iter != g_MemInfoMap.cend())
{
if (Alignment > 0)
_aligned_free(Ptr);
else
free(Ptr);
g_TotalMemDeallocation += Iter->second.Size;
g_MemInfoMap.erase(Iter);
}
else
{
std::cout << "Attempt to delete invalid ptr: " << std::ios::hex << Ptr << std::endl;
}
}

void DumpMemoryInfo()
{
using std::cout;
using std::endl;
cout << "Total memeory allocation: " << g_TotalMemAllocation << " Bytes" << endl;
cout << "Total memory deallocation: " << g_TotalMemDeallocation << " Bytes" << endl;
if (g_MemInfoMap.size() > 0)
{
cout << "Memory leak detected: " << g_TotalMemAllocation - g_TotalMemDeallocation << " Bytes" << endl;
for (auto const& Iter : g_MemInfoMap)
{
auto const& Info = Iter.second;
cout << Info.SourceFile << "\tLine: " << Info.LineNumber << "\tSize: " << Info.Size
<< "\tAddress: " << std::ios::hex << Iter.first << endl;
}
}
}

几个小细节:

除了基本的malloc和free,还需要跟踪对aligned malloc的调用,因为有时候必须使用对齐的内存,这一部分不能漏掉。

跟踪函数需要加锁防止多线程环境下出现bug

测试代码:

#include "MemCheck.h"
using namespace std;

int main()
{
void* p1 = malloc(10);
void* p2 = malloc(20);
void* p3 = malloc(30);
free(p3);
free(p2);
DumpMemoryInfo();
return 0;
}


输出:
Total memeory allocation: 60 Bytes

Total memory deallocation: 50 Bytes

Memory leak detected: 10 Bytes

main.cpp    Line: 6        Size: 10        Address: 204800E66128

在使用的时候,需要把MemCheck.h头文件放在所有的头文件最后。因为我们只想检测自己程序中的内存泄漏,不需要其它库中的内存分配信息。

这个程序只能检测malloc和free的调用,对于new和delete,情况会棘手一些。对于new的调用,可以像malloc一样用宏替换掉,然后调用自定义的operator new。比如可以这么写:

void* operator new(std::size_t MemSize, const char* SourceFile, std::size_t LineNumber);
void* operator new[](std::size_t MemSize, const char* SourceFile, std::size_t LineNumber);

#define new new (__FILE__, __LINE__)

对于delete,由于目前C++ 的operator delete只能传递一个指针参数,所以只能重载全局的::operator delete。但如果重载了全局delete,所有的调用都会被影响,例如STL容器的默认分配器std::allocator中就使用了全局::operator delete,这样其他库中的内存信息就会干扰检测结果。

一种不太雅观的方法就是所有需要检测new和delete的Class都继承一个基类,然后这个基类重载new和delete记录分配信息,这样就不会影响到其他库
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 内存管理