在 Linux 下用 C++ 查内存泄漏,常用手段从“轻量级→专业工具”逐步深入。下面按实用顺序给你一套排查思路。
new 必须有 deletemalloc 必须有 freeFoo* p = new Foo();
func(); // 若抛异常,p 泄漏
delete p;
用智能指针更安全:std::unique_ptr<Foo> p = std::make_unique<Foo>();
✅ 推荐:优先用 std::shared_ptr / unique_ptr
-fsanitize最简单、最推荐(开发阶段)
g++ -fsanitize=address -g main.cpp -o main
./main
泄漏示例输出:
==12345==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 40 byte(s) in 1 object(s)
✅ 优点:
⚠️ 注意:
sudo apt install valgrind
valgrind --leak-check=full --show-leak-kinds=all ./main
输出示例:
definitely lost: 64 bytes in 1 blocks
✅ 优点:
-g 更好)❌ 缺点:
void* operator new(size_t size) {
std::cout << "alloc " << size << "\n";
return malloc(size);
}
适合:
LD_PRELOAD=/usr/lib/libtcmalloc.so HEAPPROFILE=./heap ./main
生成:
heap.0001.heap
分析:
pprof --text ./main heap.0001.heap
✅ 适合:
| 场景 | 建议 |
|---|---|
| 开发调试 | AddressSanitizer |
| 本地详细分析 | Valgrind |
| 线上服务 | tcmalloc / jemalloc |
| 容器环境 | ASan + 日志 |
#include <iostream>
int main() {
int* p = new int[10];
// 忘记 delete
}
g++ -fsanitize=address -g test.cpp -o test
./test
如果你愿意,可以:
我可以帮你具体看。