思路就是覆盖原有的malloc和free函数,并记录内存申请和释放情况
struct MEM_INFO
{
int m_addr;
int m_size;
char m_strFile[1024];
int m_nLine;
};
hash_map<int, MEM_INFO> hstbl;
void* xmalloc(unsigned int size, const char* strFile, int nLine)
{
void* pRet = malloc(size);
MEM_INFO info;
info.m_addr = (int)pRet;
info.m_size = size;
strcpy(info.m_strFile, strFile);
info.m_nLine = nLine;
hstbl[info.m_addr] = info;
return pRet;
}
void xfree(void* p)
{
hash_map<int, MEM_INFO>::iterator it = hstbl.find((int)p);
if(it == hstbl.end()) return;
free(p);
hstbl.erase(it);
}
#define malloc(x) xmalloc(x, __FILE__, __LINE__)//调用malloc的文件以及对应的行
#define free(x) xfree(x)
void PrintLeak()
{
hash_map<int, MEM_INFO>::iterator it = hstbl.begin();
for (; it != hstbl.end(); it++)
{
cout<<"Memory leak at File: "<<it->second.m_strFile<<
" line: "<<it->second.m_nLine<<" address: "<<it->second.m_nLine
<<" size: "<<it->second.m_size<<endl;
cout<<"******************************************************************"<<endl;
}
}
void test()
{
void* p = malloc(sizeof(int));
void* q = malloc(sizeof(int));
free(p);
PrintLeak();
}
本文介绍了一种通过覆盖原有malloc和free函数实现内存泄漏检测的方法,包括如何记录内存申请和释放情况,以及如何通过宏调用实现对这些操作的统一管理。通过实例演示了内存泄漏的检测过程和清理步骤。

被折叠的 条评论
为什么被折叠?



