本文共 1154 字,大约阅读时间需要 3 分钟。
1个解决方案中可以包含多个工程
有几种方法可以跟踪内存使用状况呢?
(1)自己实现malloc(new内部也是使用malloc实现的),在里面进行跟踪 (2)推荐使用内存检测工具进行跟踪: Linux:valgrind,dmalloc,efence Windows:visual leak detector (3)自己编写小型的内存跟踪器:重载operator new和operator delete来进行跟踪 new operator等价于operator new先分配内存 + 如果是一个类对象还会调用构造函数,所以可以在operator new中跟踪在哪一个文件哪一行分配了内存头文件的包含次序,为了防止一些隐含的依赖:C库、C++库、其他库.h、项目中的.h
eg:编写测试程序测试内存泄漏时发生的情况
P53\CalculatorTest\main.cpp#includeusing namespace std;#include "DebugNew.h"int main(void){ int* p =new int; // delete p; return 0;}
测试:
eg:P53\CalculatorTest\main.cpp
#includeusing namespace std;#include "DebugNew.h"int main(void){ int* p =new int; delete p; return 0;}
#includeusing namespace std;#include "DebugNew.h"int main(void){ int* p =new int; delete p; int* p2 = new int[5]; //delete[] p2; return 0;}
测试:
为啥要重载operator delete[]运算的原因?
转载地址:http://ljfzz.baihongyu.com/