交叉编译gperftools的tcmalloc库检测内存泄露
作者:互联网
tcmalloc全称Thread-Caching Malloc,即线程缓存的malloc,实现了高效的多线程内存管理,用于替代系统的内存分配相关的函数(malloc、free,new,new[]等)
有多种使用方法,这里介绍一种不用改动代码的方法
下载
https://github.com/gperftools/gperftools/releases/
解压
tar -xvf gperftools-2.9.1.tar.gz
cd gperftools-2.9.1/
交叉编译
./configure --host=arm-openwrt-linux --prefix=`pwd`/install
库传到板子上, 这里板子用的是adb
cd install/
adb push lib/libtcmalloc.so.4.5.9 /usr/lib/libtcmalloc.so
adb push bin/pprof /sdcard/
板子上设置环境变量
export LD_PRELOAD="/usr/lib/libtcmalloc.so"
export HEAPCHECK=normal
编译测试程序生成a.out,然后在板子上测试运行程序a.out, 其代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void func()
{
int *p = (int *)malloc(4);
//free(p); 这里注释掉,用来做测试
printf("hello world!\n");
}
int main(int argc, char **argv)
{
func();
return 0;
}
输出如下,提示内存泄露
root@(none):/# /sdcard/a.out WARNING: Perftools heap leak checker is active -- Performance may suffer hello world! Have memory regions w/o callers: might report false leaks Leak check _main_ detected leaks of 4 bytes in 1 objects The 1 largest leaks: *** WARNING: Cannot convert addresses to symbols in output below. *** Reason: Cannot find 'pprof' (is PPROF_PATH set correctly?) *** If you cannot fix this, try running pprof directly. Leak of 4 bytes in 1 objects allocated from: @ 1051c @ 10554 @ 402e8e24 If the preceding stack traces are not enough to find the leaks, try running THIS shell command: pprof /sdcard/a.out "/tmp/a.out.18650._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --gv
要查看更详细的信息需要用pprof查看,如上面的打印表示生成了一个.heap文件,把这个文件放到pc机linux系统上
adb pull /tmp/a.out.31993._main_-end.heap
pc端重新编译gperftools,然后在pc机上使用gperftools-2.9.1编译出来的pprof查看
gperftools-2.9.1/install/bin> ./pprof /home/zm/download/a.out "/home/zm/download/a.out.18650._main_-end.heap" --inuse_objects --lines --heapcheck --edgefraction=1e-10 --nodefraction=1e-10 --text Using local file /home/zm/download/a.out. Using local file /home/zm/download/a.out.18650._main_-end.heap. Total: 1 objects 1 100.0% 100.0% 1 100.0% func :0 0 0.0% 100.0% 1 100.0% 00000000402e8e23 0 0.0% 100.0% 1 100.0% main :0
可以看到这里准确定位到func函数中。
作者:帅得不敢出门
标签:--,pprof,内存,heap,gperftools,main,100.0%,tcmalloc 来源: https://blog.csdn.net/zmlovelx/article/details/114549246