C++通用內存檢查
由map的升序排列和折半查找想到可以解決一些實際的問題,比如堆內存的管理
#include <cstdio>include <map>
define MEM_NEW(T,n) mem_alloc<T>(n, TIME, FILE, LINE)
define MEM_DELETE(p) if(p)\
{\ mem_free(p);\ p = NULL;\ };
define MEM_CHECK() mem_check()
struct AllocInfo { const char time; const char file; int line; };
std::map<void*,AllocInfo> g_UserMem;
/使用模板函數為了new的時候明確類型從而調用構造函數 明確返回此類的對象指針不必類型轉換/ template<typename T> T mem_alloc(int _size, const char _time, const char _file, const int _line) { void p = static_cast<void>(new T[_size]); if(p) { AllocInfo _Info = {_time,_file,_line}; g_UserMem.insert(make_pair(p,_Info)); return static_cast<T>(p); } else {
return NULL; } }/使用模板函數為了delete時明確類型從而調用析構函數 找到key對應的內存地址返回迭代器清除容器成員/ template<typename T> void mem_free(T _point) { delete[] _point; g_UserMem.erase(g_UserMem.find(static_cast<void>(_point))); }
void mem_check() { printf("----------[Memory Check]----------\n");
if(!g_UserMem.size()) { printf("Memory have all been released\n"); return; } printf("Exist memory hasn't be freed:\n"); std::map<void*,AllocInfo>::iterator it_map = g_UserMem.begin(); for(;it_map!=g_UserMem.end();++it_map) { if(it_map->first) { printf("Memory Allocation Time:[%s]\n\t%s - Line:%d\n",it_map->second.time, it_map->second.file, it_map->second.line); } }
}</pre>
由于C++的模版不支持頭文件和CPP文件分離 所以以上函數定義在頭文件中
下面是測試代碼
將平時的new和delete操作替換成宏函數即可,在程序退出前檢查
#include <iostream> #include "MemCheck.h" using namespace std; class A { public: A() { cout<<"A"<<endl; } ~A() { cout<<"~A"<<endl; } }; int main() { A *p = MEM_NEW(A,1); MEM_DELETE(p); MEM_CHECK(); getchar(); return 0; }來自:http://my.oschina.net/mlgb/blog/262943