在 CentOS 上 C++ 出现“内存泄漏”通常不是系统本身的问题,而是程序、库或运行环境导致的。下面从常见原因 → 排查方法 → 解决建议系统性说明。
int* p = new int[10];
delete p; // ❌ 应该是 delete[]
或:
malloc / new 后忘记释放
✅ 建议:
new ↔ deletenew[] ↔ delete[]std::unique_ptr<int> p(new int(10));
std::shared_ptr<int> q = std::make_shared<int>(10);
std::vector<int> v;
while (true) {
v.push_back(i++);
}
即使函数结束,全局/静态容器仍驻留。
✅ 建议:
clear()很多 CentOS 服务程序使用:
这些库如果:
都会造成“看似泄漏”。
✅ 示例(libcurl):
curl_global_init(CURL_GLOBAL_ALL);
// 程序结束必须
curl_global_cleanup();
长期运行的服务(如后台 daemon):
表现:
top 中 RES 一直涨✅ 解决:
export MALLOC_ARENA_MAX=2
或修改 /etc/sysctl.conf
| 系统 | glibc |
|---|---|
| CentOS 7 | 2.17 |
| CentOS 8 | 2.28 |
不同 glibc 对内存回收策略不同,可能“看起来泄漏”。
yum install valgrind
valgrind --leak-check=full ./your_program
看:
definitely lost
indirectly lost
g++ -fsanitize=address -g main.cpp
./a.out
优点:
top
pmap -x <pid>
cat /proc/<pid>/status | grep VmRSS
如果:
export MALLOC_TRIM_THRESHOLD_=100000
[Service]
MemoryMax=512M
超了会被 kill,但不是泄漏。
✅ 写 C++:
✅ 运行服务:
MALLOC_ARENA_MAX如果你愿意,可以:
我可以帮你精确定位是哪一行泄漏。