这里是一个简单的内存泄漏自动检查机制。只适用于单线程情况下。工作原理就是将已经分配的内存用一个双向链表串联起来,释放内存时从链表里删除。在程序退出时,将链表中未释放的内存打印出来。同时在内存块中保存文件名和行号,用于定位内存分配地址。
001 // placement_new.cpp : Defines the entry point for the console application.
002 //
003
004 #include "stdafx.h"
005 #include
006 #include
007
008 #define ASSERT assert
009 char buff[1024];
010
011 using namespace std;
012
013 struct MEMORY_TAG
014 {
015 int nSize;
016 const char* szFile;
017 int nLine;
018 MEMORY_TAG* pPrev;
019 MEMORY_TAG* pNext;
020 };
021
022 MEMORY_TAG g_header = {0, 0, 0, 0, 0};
023 // 打印出所有未释放的内存
024 void DumpUnAllocatedMem()
025 {
026 for(MEMORY_TAG* pEntry = g_header.pNext; pEntry; pEntry = pEntry->pNext)
027 {
028 printf("%s(%d) : leak %d bytes\n", pEntry->szFile pEntry->szFile : "", pEntry->nLine, pEntry->nSize);
029 }
030 }
031 // 统计已经分配的内存块数和字节数