参考 http://ju.outofmemory.cn/entry/24487
编译gperftools
- 编译并安装libunwind,命令如下所示。注意这个过程很关键,否者heap profiler产生的数据文件都会是空的。我和小师妹在这个问题上纠结了好久,剑豪也遇到过这个问题。幸好今天听亚夫讲到libunwind,才最终解决了这个问题。
1727 ./configure --prefix=/home/liminghao/tools/libunwind/ CFLAGS=-U_FORTRIFY_SOURCE
1728 make
1729 make install
1753 ./configure --prefix=/home/liminghao/tools/gperftools LDFLAGS=-L/home/liminghao/tools/libunwind/lib CPPFLAGS=-I/home/liminghao/tools/libunwind/include
1754 make
1755 make install
使用heap profiler
实例代码
#include <iostream>
using namespace std;
const uint32_t len = 102400;
char* foo()
{
char* p = new char[len];
memset(p, 0, len);
return p;
}
char* bar()
{
char* p = new char[len];
memset(p, 0, len);
return p;
}
int main(int argc, const char *argv[])
{
for (int i = 0; i < 1000; i++) {
char* f = foo();
memcpy(f, "abc", 3);
char* b = bar();
memcpy(b, "abc", 3);
}
return 0;
}
编译命令
g++ -g google_perf_test.cpp -o google_perf_test
运行命令
$ env LD_PRELOAD="/home/henshao/googleperf_install/lib/libtcmalloc.so" HEAPPROFILE="./perf_log/perf_leak.log" ./google_perf_test
Starting tracking the heap
Dumping heap profile to ./perf_log/perf_leak.log.0001.heap (100 MB currently in use)
Dumping heap profile to ./perf_log/perf_leak.log.0002.heap (Exiting)
分析结果
从下面的结果可以看出,foo和bar两个函数分别申请了100MB的内存。
$ pprof --text google_perf_test perf_log/perf_leak.log.0003.heap
Using local file google_perf_test.
Using local file perf_log/perf_leak.log.0003.heap.
Total: 200.0 MB
.0 50.0% 50.0% 100.0 50.0% bar
.0 50.0% 100.0% 100.0 50.0% foo
.0 0.0% 100.0% 0.0 0.0% PrintStats
.0 0.0% 100.0% 0.0 0.0% std::string::_Rep::_S_create
.0 0.0% 100.0% 0.0 0.0% __static_initialization_and_destruction_0@29a30
.0 0.0% 100.0% 0.0 0.0% 0x00002b71bca8adcf
.0 0.0% 100.0% 0.0 0.0% __cxa_finalize
.0 0.0% 100.0% 0.0 0.0% __do_global_ctors_aux
.0 0.0% 100.0% 0.0 0.0% __do_global_dtors_aux
.0 0.0% 100.0% 200.0 100.0% __libc_start_main
.0 0.0% 100.0% 0.0 0.0% _fini
.0 0.0% 100.0% 0.0 0.0% _init
.0 0.0% 100.0% 200.0 100.0% _start
.0 0.0% 100.0% 0.0 0.0% exit
.0 0.0% 100.0% 200.0 100.0% main
.0 0.0% 100.0% 0.0 0.0% std::basic_string::basic_string
.0 0.0% 100.0% 0.0 0.0% std::string::_S_copy_chars
小帮助
- The first column contains the direct memory use in MB.
- The fourth column contains memory use by the procedure and all of its callees.
- The second and fifth columns are just percentage representations of the numbers in the first and fourth columns.
- The third column is a cumulative sum of the second column (i.e., the kth entry in the third column is the sum of the first k entries in the second column.)
本文详细介绍了如何编译安装gperftools及其依赖库libunwind,并通过一个示例展示了如何使用gperftools中的heapprofiler进行内存泄漏检测。包括配置编译参数、编译命令及运行时环境变量设置。
697

被折叠的 条评论
为什么被折叠?



