在 CentOS 上排查 C++ 内存泄漏,常用手段从“快速定位”到“精细分析”有以下几个层次。下面按实战推荐顺序说明。
yum install -y valgrind
valgrind --tool=memcheck --leak-check=full \
--show-leak-kinds=all \
--log-file=valgrind.log \
./your_program
definitely lost:确定泄漏indirectly lost:间接泄漏still reachable:程序退出时未释放(未必是 bug)✅ 不需要改代码
✅ 定位到具体行号
❌ 程序运行慢(5–10 倍)
g++ -fsanitize=address -g -O1 -fno-omit-frame-pointer main.cpp -o app
./app
==12345==ERROR: AddressSanitizer: leak of 1024 byte(s)
#0 0x... in malloc
#1 0x... in main main.cpp:20
✅ 比 Valgrind 快
✅ 定位精准
❌ 需要重新编译
top / pstop -p $(pidof your_program)
关注:
RES 是否持续增长/proc/<pid>/statuscat /proc/$(pidof your_program)/status | grep Vm
#include <mcheck.h>
int main() {
mtrace();
// your code
return 0;
}
export MALLOC_TRACE=mtrace.log
./app
mtrace ./app mtrace.log
✅ 轻量
❌ 只支持 malloc/free
如果是:
可考虑:
yum install jemalloc
LD_PRELOAD=/usr/lib64/libjemalloc.so.1 ./app
并可导出内存 profile。
new 但没 deletevector, map)shared_ptr)top 看内存是否增长ASan 本地复现Valgrind 精确定位如果你愿意,可以:
我可以帮你定制最合适的排查方案。