内存泄露是指程序动态申请的内存在使用结束后并没有释放,导致系统无法正常回收。
例如:
1 // a test of memory leaked 2 #include <iostream> 3 using namespace std; 4 int main() { 5 char* ch = new char[10]; 6 cout << "ch = " << *ch << endl; 7 return 0; 8 }
在大型系统中,如果发生内存泄露,随着系统长时间的运行,会导致系统性能下降(内存泄露致使可用内存越来越少)甚至崩溃(泄漏量很大,导致所有内存被占满)。
内存泄露问题是比较严重而且比较难定位,基于这个原因,在大型系统中可以选择定制自己的内存操作组件。
1 // the component of memory 2 #include <iostream> 3 class MyMemory { 4 public: 5 MyMemory() : m_couple(0) {} 6 ~MyMemory() {} 7 void* alloc(int size) { 8 void* ret = NULL; 9 ret = new char[size]; 10 m_couple++; 11 return ret; 12 } 13 14 void free(void* p) { 15 m_couple--; 16 delete []p; 17 } 18 19 bool leak() { 20 if (m_couple == 0) { 21 std::cout << "there isn't memory leaked;" << std::endl; 22 return false; 23 } else if (m_couple < 0) { 24 std::cout << "there is memory double free;" << std::endl; 25 return true; 26 } else { 27 std::cout << "there is memory leaked;" << std::endl; 28 return true; 29 } 30 } 31 32 // use to record the stack of operator of memory 33 void logStack() {} 34 35 private: 36 int m_couple; 37 }; 38 39 int main() { 40 MyMemory *mem = new MyMemory(); 41 void* ch = mem->alloc(10); 42 //mem->free(ch); 43 mem->leak(); 44 delete mem; 45 return 0; 46 }
备注:
这个设计有缺陷,还有待完善,但基本上可以说明问题,可以补充的部分如下:
(1)单独设计一个struct用来保存每次申请内存的堆栈信息,这样如果有内存泄露,将泄露的堆栈打印到文件中。
(2)free在设计上有缺陷
(3)无法统计每次申请内存大小,如果设计成struct可以弥补
(4)无法统计出第三方库的内存情况
(5)如果项目比较大,要让每个使用内存的文件都包含该文件
可以单独的设计一个map结构,用来保存每次申请内存的堆栈情况,只要有内存申请,就将调用堆栈以struct形式放进map中,该块内存释放,就将该堆栈从map中删除。
参考链接:http://blog.csdn.net/mishifangxiangdefeng/article/details/50552687