思路就是覆盖原有的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();
}