交叉编译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"

编译测试程序生成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;
}

HEAPCHECK=normal /sdcard/a.out

输出如下,提示内存泄露

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函数中。

作者:帅得不敢出门

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值