近期尝试使用gperftools对C++内存泄露进行排查,所以对gperftools进行了一些了解。gperftools是google用来进行程序性能优化的工具集合,主要包括tcmalloc和profiler两个库。其可以提供如下的功能:
- tcmalloc:与glibc中的malloc函数相比,tcmalloc的内存分配效率要远高于malloc,可以提高高并发的性能 ,降低系统的负载
- cpu profiler:对程序中各个函数使用的CPU情况进行监控探测
- heap checker:对程序是否发生内存泄露进行检测
- heap profiler:对程序中申请的内存区域进行监控
heap checker
使用
对于使用heap checker的使用,需要注意的是一般是对整个程序进行检测,要求这个程序会自动退出,而不是那种会不停的运行的服务。其实gperftools的官方文档中说当发现内存泄露的同时会通过exit()使程序退出并打印相关的内存信息。
In this case, the heap-checker starts tracking memory allocations before the start of main(), and checks again at program-exit. If it finds any memory leaks – that is, any memory not pointed to by objects that are still “live” at program-exit – it aborts the program (via exit(1)) and prints a message describing how to track down the memory leak (using pprof).
对于heap checker的使用有两种方法:
设置LD_PRELOAD 来预加载tcmalloc库,然后执行相关的运行命令,例如:
LD_PRELOAD=/usr/lib64/libtcmalloc.so HEAPCHECK=normal ./example1
在编译时使用静态库进行连接,然后执行相关的运行命令,例如: