内存池tcmalloc的使用

tcmalloc

由于项目引入了协程,之前使用的内存泄漏和越界检测工具asan就不能用了,asan官方说对协程的支持不够。 所以只能换一个工具,tcmalloc是一个不错的替代品,同时tcmalloc还提供了内存管理的功能,在一个2.8GHz 4核的机器上普通malloc和free一次耗时300ns,tcmalloc同样的功能只需要50ns(数据来源于网络)。 记录一个检测内存泄漏的例子:

#test.cpp

#include <iostream>
int test()
{
    char* p = new char[100];
    return 1;
}

int main()
{
    test();
    return 1;
}


g++ -g -o test test.cpp

#设置这三个环境变量可以让程序不用重新编译

export HEAPCHECK=normal
export LD_PRELOAD=./commonlib/libtcmalloc.so
export PPROF_PATH=./share_bin/pprof

./test

WARNING: Perftools heap leak checker is active -- Performance may suffer
Have memory regions w/o callers: might report false leaks
Leak check _main_ detected leaks of 100 bytes in 1 objects
The 1 largest leaks:
Using local file ./test.
Leak of 100 bytes in 1 objects allocated from:
        @ 40074a test
        @ 40075e main
        @ 3a5341ed5d __libc_start_main
        @ 4005f9 _start


If the preceding stack traces are not enough to find the leaks, try running THIS shell command:

pprof ./test "/tmp/test.17307._main_-end.heap" --inuse_objects --lines --heapcheck  --edgefraction=1e-10 --nodefraction=1e-10 --gv

If you are still puzzled about why the leaks are there, try rerunning this program with HEAP_CHECK_TEST_POINTER_ALIGNMENT=1 and/or with HEAP_CHECK_MAX_POINTER_OFFSET=-1
If the leak report occurs in a small fraction of runs, try running with TCMALLOC_MAX_

可以看到检测出了内存泄漏的堆栈信息,以及最上一层存在泄漏的函数test()