在 CentOS 上用 C++ 出现“内存泄漏”,通常不是 CentOS 本身的问题,而是程序、依赖库或运行环境导致的。下面按常见原因 → 排查方法 → 解决建议系统说明。
new / malloc 没有释放int* p = new int[100];
// 忘记 delete[] p;
✅ 解决:
new ↔ deletenew[] ↔ delete[]malloc ↔ free✅ 推荐:
std::unique_ptr<int[]> p(new int[100]);
std::shared_ptr<T> sp = std::make_shared<T>();
void f() {
int* p = new int[10];
throw 1;
delete[] p; // 不会执行
}
✅ 解决:
std::vector<int> v;
while (true) v.push_back(1);
✅ 解决:
clear()static std::map<int,int> cache;
cache[id] = value; // 永不清空
free() 返回的结构*_cleanup() / *_free()✅ 排查:
ldd your_program
✅ 建议:
yum update
保持系统一致
top 看到 RSS 不降 ≠ 泄漏✅ 验证:
cat /proc/<pid>/smaps
pthread_create(...);
// 没 pthread_join / detach
yum install valgrind
valgrind --leak-check=full ./your_app
g++ -fsanitize=address -g main.cpp
./a.out
while true; do
ps -o rss= -p <pid>
sleep 1
done
如果 持续增长且不回落 → 真泄漏
new 都有 delete如果你愿意,可以:
我可以直接帮你定位是哪一类内存泄漏。