##1、安装 到 https://github.com/gperftools/gperftools 下载,然后:
$ sudo apt-get install autoconf
$ sudo apt-get install automake
$ sudo apt-get install libtool
$ ./autogen.sh
$ ./configure
$ make
$ sudo make install
$ su root
# echo /usr/local/lib > /etc/ld.so.conf.d/libtcmalloc.conf
# exit
$ sudo ldconfig
2、检测内存的使用
#include <iostream>
#include <unistd.h>
using namespace std;
class Person {
private:
string name;
public:
void setName(string name) {
this->name = name;
}
const string& getName() {
return this->name;
}
};
int main() {
Person *someone;
for(int i=0; i<10; ++i) {
someone = new Person;
someone->setName("Li Ming");
cout << someone->getName() << endl;
// sleep(2);
}
}
$ g++ example.cpp -ltcmalloc
$ HEAPPROFILE=test ./a.out
程序运行结束后,当前目录会出现 test.0001.heap
文件。
生成pdf:
$ pprof --pdf a.out test.0001.heap > test.pdf
3、查看内存泄漏
$ export PPROF_PATH=/usr/local/bin/pprof
$ HEAPCHECK=normal ./a.out
WARNING: Perftools heap leak checker is active -- Performance may suffer
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Li Ming
Have memory regions w/o callers: might report false leaks
Leak check _main_ detected leaks of 400 bytes in 20 objects
The 2 largest leaks:
Using local file ./a.out.
Leak of 320 bytes in 10 objects allocated from:
@ 7fb33ee69249 std::string::_Rep::_S_create
@ 7fb33ee6a971 std::string::_S_construct
@ 7fb33ee6ad88 std::basic_string::basic_string
@ 400d8e main
@ 7fb33e7f5f45 __libc_start_main
@ 400c79 _start
Leak of 80 bytes in 10 objects allocated from:
@ 400d5e main
@ 7fb33e7f5f45 __libc_start_main
@ 400c79 _start
If the preceding stack traces are not enough to find the leaks, try running THIS shell command:
pprof ./a.out "/tmp/a.out.31217._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --gv
If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_FREE_QUEUE_SIZE of few hundred MB or with TCMALLOC_RECLAIM_MEMORY=false, it might help find leaks more repeatab
Exiting with error code (instead of crashing) because of whole-program memory leaks
g++ example03.cpp -ltcmalloc
HEAPPROFILE=test ./a.out
错误解决
1、`sh: 1: dot: not found`
sudo apt-get install graphviz
2、"gv": No such file
参考
tcmalloc安装,使用以及解析(一)
error while loading shared libraries: xxx.so.x"错误的原因和解决办法
其他
https://github.com/gperftools/gperftools