#include <iostream>
#include <stdlib.h>
struct MemIns
{
void *pMem;
int m_nSize;
char m_szFileName[256];
int m_nLine;
MemIns *pNext;
};
class MemManager
{
public:
MemManager();
~MemManager();
private:
MemIns *m_pMemInsHead;
int m_nTotal;
public:
static MemManager* GetInstance();
void Append(MemIns *pMemIns);
void Remove(void *ptr);
void Dump();
};
void *operator new(size_t size, const char*szFile, int nLine);
void operator delete(void*ptr, const char*szFile, int nLine);
void operator delete(void*ptr);
void *operator new[] (size_t size, const char*szFile, int nLine);
void operator delete[](void*ptr, const char*szFile, int nLine);
void operator delete[](void *ptr);
#include"memchecker.h"
#include<stdio.h>
#include<malloc.h>
#include<string.h>
MemManager::MemManager()
{
m_pMemInsHead=NULL;
m_nTotal=NULL;
}
MemManager::~MemManager()
{
}
void MemManager::Append(MemIns *pMemIns)
{
pMemIns->pNext=m_pMemInsHead;
m_pMemInsHead = pMemIns;
m_nTotal+= m_pMemInsHead->m_nSize;
}
void MemManager::Remove(void *ptr)
{
MemIns * pCur = m_pMemInsHead;
MemIns * pPrev = NULL;
while(pCur)
{
if(pCur->pMem ==ptr)
{
if(pPrev)
{
pPrev->pNext =pCur->pNext;
}
else
{
m_pMemInsHead =pCur->pNext;
}
m_nTotal-=pCur->m_nSize;
free(pCur);
break;
}
pPrev = pCur;
pCur = pCur->pNext;
}
}
void MemManager::Dump()
{
MemIns *pp = m_pMemInsHead;
while(pp)
{
printf( "File is %s\n", pp->m_szFileName );
printf( "Size is %d\n", pp->m_nSize );
printf( "Line is %d\n", pp->m_nLine );
pp = pp->pNext;
}
}
void PutEntry(void *ptr,int size,const char*szFile, int nLine)
{
MemIns * p = (MemIns *)(malloc(sizeof(MemIns)));
if(p)
{
strcpy(p->m_szFileName,szFile);
p->m_nLine = nLine;
p->pMem = ptr;
p->m_nSize = size;
MemManager::GetInstance()->Append(p);
}
}
void RemoveEntry(void *ptr)
{
MemManager::GetInstance()->Remove(ptr);
}
void *operator new(size_t size,const char*szFile, int nLine)
{
void *ptr = malloc(size);
PutEntry(ptr,size,szFile,nLine);
return ptr;
}
void operator delete(void *ptr)
{
RemoveEntry(ptr);
free(ptr);
}
void operator delete(void*ptr,const char *file, int line)
{
RemoveEntry(ptr);
free(ptr);
}
void*operator new[] (size_t size,const char* szFile,int nLine)
{
void * ptr = malloc(size);
PutEntry(ptr,size,szFile,nLine);
return ptr;
}
void operator delete[](void *ptr)
{
RemoveEntry(ptr);
free(ptr);
}
void operator delete[](void*ptr,const char*szFile,int nLine)
{
RemoveEntry(ptr);
free(ptr);
}
#define new new(__FILE__,__LINE__)
MemManager m_memTracer;
MemManager*MemManager::GetInstance()
{
return &m_memTracer;
}
int main(void)
{
int *plen =new int ;
*plen=10;
delete plen;
char *pstr=new char[35];
strcpy(pstr,"hello memory leak");
m_memTracer.Dump();
return 0;
}
运行结果
[root@test memcheck]# ./memcheck
File is memchecker.cpp
Size is 35
Line is 148