我有一个非常简单的 C++ 程序。
#include <iostream>
int main()
{
std::cout << "HI" << std::endl;
return 0;
}
我在 Mac 上使用命令 c++ --std=c++11 leak.cpp
编译它。
当我使用 valgrind --leak-check=full ./a.out
进行调试时,我得到以下输出:
==2187== HEAP SUMMARY:
==2187== in use at exit: 38,906 bytes in 429 blocks
==2187== total heap usage: 508 allocs, 79 frees, 45,074 bytes allocated
==2187==
==2187== LEAK SUMMARY:
==2187== definitely lost: 0 bytes in 0 blocks
==2187== indirectly lost: 0 bytes in 0 blocks
==2187== possibly lost: 0 bytes in 0 blocks
==2187== still reachable: 4,096 bytes in 1 blocks
==2187== suppressed: 34,810 bytes in 428 blocks
==2187== Reachable blocks (those to which a pointer was found) are not shown.
==2187== To see them, rerun with: --leak-check=full --show-leak-kinds=all
原来有 4096 个字节“仍然可达”。如果我删除 cout
语句,则不再有“仍可访问”的字节。
为什么输出到std::cout
会导致内存泄漏?
最佳答案
这可能是泄漏报告中的误报。 Valgrind 只能这么聪明;您的标准库实现采用了某些 Valgrind 没有特殊情况的自由。
我更担心弄清楚为什么这个小程序要执行 508 次分配,总计 45,074 字节。
关于c++ - std::cout 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468149/