除了 Mike 的回答(覆盖 Malloc)之外,您还可以覆盖 Visual Studio 中的 new 和 delete 运算符。
免责声明:我早在 2004 年就在网上找到了这段代码,并将其包含在一个 C++ 项目中。我不知道原始出处
下面是一个代码示例(我将其作为头文件 memleak.h 包含在内)。这是相当旧的代码,因此编译时可能会出错!但是,它确实说明了如何覆盖 new 和 delete。它还将未释放的内存转储到文件中。如果定义_DEBUG 包含在您的代码中,此代码将生效。
最好的问候,
#include <iostream>
#include <list>
using namespace std;
//void DumpUnfreed();
//void AddTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum);
//void RemoveTrack(DWORD addr);
typedef struct
{
DWORD address;
DWORD size;
char file[64];
DWORD line;
} ALLOC_INFO;
typedef list<ALLOC_INFO*> AllocList;
AllocList *allocList;
void AddTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum)
{
ALLOC_INFO *info;
if(!allocList)
{
allocList = new(AllocList);
}
info = new(ALLOC_INFO);
info->address = addr;
strncpy(info->file, fname, 63);
info->line = lnum;
info->size = asize;
allocList->insert(allocList->begin(), info);
};
void RemoveTrack(DWORD addr)
{
AllocList::iterator i;
if(!allocList)
return;
for(i = allocList->begin(); i != allocList->end(); i++)
{
if((*i)->address == addr)
{
allocList->remove((*i));
break;
}
}
};
void DumpUnfreed()
{
AllocList::iterator i;
DWORD totalSize = 0;
char buf[1024];
sprintf(buf, "-----------------------------------------------------------\n");
OutputDebugString(buf);
OutputDebugString("DSP.DLL: Detecting unfreed memory...\n");
if(!allocList)
{
OutputDebugString("No memory allocations were tracked!\n");
return;
}
for(i = allocList->begin(); i != allocList->end(); i++)
{
sprintf(buf, "%-50s:\t\tLINE %d,\t\tADDRESS %d\t%d unfreed\n",
(*i)->file, (*i)->line, (*i)->address, (*i)->size);
OutputDebugString(buf);
totalSize += (*i)->size;
}
sprintf(buf, "-----------------------------------------------------------\n");
OutputDebugString(buf);
sprintf(buf, "DSP.DLL Total Unfreed: %d bytes\n", totalSize);
OutputDebugString(buf);
sprintf(buf, "-----------------------------------------------------------\n");
OutputDebugString(buf);
};
#ifdef _DEBUG
inline void * __cdecl operator new(unsigned int size,
const char *file, int line)
{
void *ptr = (void *)malloc(size);
AddTrack((DWORD)ptr, size, file, line);
return(ptr);
};
inline void __cdecl operator delete(void *p)
{
RemoveTrack((DWORD)p);
free(p);
};
inline void * __cdecl operator new[ ] (unsigned int size, const char *file, int line)
{
void *ptr = (void *)malloc(size);
AddTrack((DWORD)ptr, size, file, line);
return(ptr);
};
inline void __cdecl operator delete[ ] (void *p)
{
RemoveTrack((DWORD)p);
free(p);
};
#endif
#ifdef _DEBUG
#define DEBUG_NEW new(__FILE__, __LINE__)
#else
#define DEBUG_NEW new
#endif
#define new DEBUG_NEW