Jemalloc 不仅实现了一种通用的malloc, 还能利用它来做内存分析和监控/调优等.

这里介绍如何利用jemalloc来检测内存泄漏问题. 并且利用LD_PRELOAD环境变量, 可以做到不需要源代码, 将jemalloc库嵌入到可执行程序中, 从而用jemalloc去malloc内存, 并进行管理. 也就是说, 每当程序中调用malloc/new时, 实际调用的是jemalloc里实现的函数.

Install

releases获取jemalloc最新版.

参考: https://github.com/jemalloc/jemalloc/blob/dev/INSTALL.md

cd ~/jemalloc_test
wget https://github.com/jemalloc/jemalloc/releases/download/5.1.0/jemalloc-5.1.0.tar.bz2
tar zxvf jemalloc-5.1.0.tar.bz2
cd jemalloc-5.1.0
./configure --prefix=/home/intzero/jemalloc_test/jemalloc_install  # 我这里装在自己目录下
make
make install
export PATH=/home/intzero/jemalloc_test/jemalloc_install/bin:$PATH

Getting Started

参考: https://github.com/jemalloc/jemalloc/wiki/Getting-Started

有几种方式将jemalloc整合到你的程序中.

  • 一种是在源代码中加入jemalloc代码, 在build代码时嵌入.
  • 另外一种是利用LD_PRELOAD环境变量, 在程序运行时就能嵌入, 不需要源代码.

另外可以通过 MALLOC_CONF环境变量来调整jemalloc.

写个demo测试一下.

vi main.cpp

#include <stdlib.h>
#include <iostream>
#include <jemalloc/jemalloc.h>
using namespace std;

void do_something(size_t i) {
    // Leak some memory.
    int *p = new int[i]; // or malloc(i * 4);
}

int main(int argc, char **argv) {
    for (size_t i = 1; i <= 1000; i++) {
        do_something(i);
    }

    cout << "jemalloc test." << endl;

    // Dump allocator statistics to stderr.
    malloc_stats_print(NULL, NULL, NULL);
    
    return 0;
}

运行:

$ g++ main.cpp -o main -I`jemalloc-config --includedir` -L`jemalloc-config --libdir` -Wl,-rpath,`jemalloc-config --libdir` -ljemalloc `jemalloc-config --libs`
$ ./main

可看到打印出来的内存信息.

Leak Checking

vi main.cpp

#include <stdlib.h>
#include <iostream>
using namespace std;

void do_something(size_t i) {
    // Leak some memory.
    int *p = new int[i]; // or malloc(i * 4);
}

int main(int argc, char **argv) {
    for (size_t i = 1; i <= 1000; i++) {
        do_something(i);
    }

    cout << "jemalloc test." << endl;
    return 0;
}

运行:

$ g++ main.cpp -o main
$ MALLOC_CONF=prof_leak:true,lg_prof_sample:0,prof_final:true LD_PRELOAD=/home/intzero/jemalloc_test/jemalloc_install/lib/libjemalloc.so.2 ./main

上面这条命令会执行./main, 并将jemalloc提前加载进去.

程序退出之后, 会生成类似jeprof.37252.0.f.heap的文件. 查看详细信息:

$ jeprof --show_bytes `which ./main` jeprof.37252.0.f.heap

Using local file jeprof.37252.0.f.heap.
Welcome to jeprof!  For help, type 'help'.
(jeprof) top
Total: 2173680 B
 2173680 100.0% 100.0%  2173680 100.0% 0x00007f8f2f7d7ac0
       0   0.0% 100.0%  2173680 100.0% 0x00007f8f2e5b1b13
       0   0.0% 100.0%  2173680 100.0% 0x00007f8f2f788581
       0   0.0% 100.0%  2173680 100.0% 0x00007f8f2f7e93a0
       0   0.0% 100.0%  2173680 100.0% _start
       0   0.0% 100.0%  2173680 100.0% do_something
       0   0.0% 100.0%  2173680 100.0% main
(jeprof) 

还可以生成call graph的PDF文件:

jeprof --show_bytes --pdf `which ./main` jeprof.37252.0.f.heap > w.pdf