安装jemalloc

1
apt install libjemalloc2

安装svg图片生成工具

1
apt install graphviz gv

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <chrono>
#include <thread>

int main() {

std::vector<int> vec;
std::map<int, int> mp;
std::string s;
for (;;) {
for (int i = 0; i < 1000; ++i) {
vec.push_back(i);
mp[rand()] = i;
s += "xxxx";
new char[4];
}
std::this_thread::sleep_for(std::chrono::microseconds(100));
}

return 0;
}

编译

1
g++ -o test -g test.cpp

运行

1
MALLOC_CONF=prof:true,lg_prof_interval:26 LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 ./test

prof:true表示打开堆检测,lg_prof_interval:26使jemalloc开启prof并且每2^26字节(64M)大小进行一次dump

生成内存泄露图

1
jeprof --pdf a.out --base=jeprof.1646511.0.i0.heap  jeprof.1646511.100.i100.heap > result.pdf

–base表示基准堆,即第一次dump的堆,后面每次dump的堆都会和基准堆进行比较,从而找出内存泄露的函数