在实际项目开发中,内存泄露问题是一个很头疼的问题,程序跑着跑着就挂了会造成巨大的损失,所以必须知道整个程序在运行过程中哪些地方内存泄露了,泄露了多少。
一般的大型项目都会有一套属于自己的内存分配机制,这样能更加容易的进行内存管理和内存跟踪,及时发现内存泄露。
#include "iostream"
#include
#include "winbase.h"
using namespace std;
void* MyAlloc(size_t size, const char* filename, int line)
{
// 分配内存
// 输出信息,此为简单例子,实际开发中会讲内存分配信息保存,程序结束时输出内存泄露的相关文件位置和信息
char str[100];
sprintf_s(str, "%s(%d) : alloc size=%dbytes", filename, line, size);
WCHAR wszClassName[256];
memset(wszClassName, 0, sizeof(wszClassName));
MultiByteToWideChar(CP_ACP, 0, str, strlen(str) + 1, wszClassName,
sizeof(wszClassName) / sizeof(wszClassName[0]));
OutputDebugString(wszClassName);
return NULL;
}
void* operator new(size_t size)
{
return MyAlloc(size, __FILE__, __LINE__);
}
void* operator new(size_t size, const char* filename, int line)
{
return MyAlloc(size, filename, line);
}
// 顺序很重要啊!!!!
#ifdef _DEBUG
#undef DEBUG_NEW
#undef new
#define DEBUG_NEW new(__FILE__,__LINE__)
#define new DEBUG_NEW
#endif
class A
{
public:
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
A* a = new A;
return 0;
}