在 CentOS 上 C++ 出现“内存泄漏”,通常不是 CentOS 本身的问题,而是 程序、库或使用方式 导致的。下面从常见原因到排查方法系统说明。
new / malloc 没有对应释放最常见、最本质原因。
int* p = new int[100];
// 忘记 delete[] p;
或:
char* c = (char*)malloc(1024);
// 忘记 free(c);
✅ 原则:
new ↔ deletenew[] ↔ delete[]malloc ↔ freevoid foo() {
int* p = new int[10];
throw std::runtime_error("error"); // 直接跳走
delete[] p; // 不会执行
}
✅ 解决方式:
std::unique_ptr<int[]> p(new int[10]);
std::vector<int> v(1000000);
v.clear(); // size=0
// 但 capacity 可能不变
✅ 真正释放:
std::vector<int>().swap(v);
有些库:
xxx_close()✅ 排查:
static std::map<int,int> cache;
程序跑很久 → cache 一直增长
✅ 本质:
有时候:
原因:
✅ 可用:
MALLOC_ARENA_MAX=2 ./your_program
✅ 可换:
jemalloctcmalloc不是泄漏,但:
top / pstop -p <pid>
看 RES 是否持续增长
yum install valgrind
valgrind --leak-check=full ./your_program
输出:
definitely lost: 1024 bytes
编译:
g++ -fsanitize=address -g main.cpp
运行直接报错位置。
valgrind --tool=massif ./app
ms_print massif.out.xxx
CentOS 上的 C++ “内存泄漏”,99% 是代码或库的问题,不是系统问题。
✅ 智能指针
✅ RAII
✅ ASan 本地测试
✅ Valgrind 上线前检查
如果你愿意,可以:
我可以帮你精准定位。