【发布时间】:2014-04-09 20:21:48
【问题描述】:
我在使用 getline 时遇到内存泄漏,我不知道为什么或如何阻止它。
这是来自 valgrind 的报告:
==26681==
==26681== HEAP SUMMARY:
==26681== in use at exit: 1,756 bytes in 73 blocks
==26681== total heap usage: 223 allocs, 150 frees, 15,523 bytes allocated
==26681==
==26681== 28 bytes in 1 blocks are possibly lost in loss record 1 of 4
==26681== at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==26681== by 0x4CCC4B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (new_allocator.h:94)
==26681== by 0x4CCD227: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long) (basic_string.tcc:631)
==26681== by 0x4CCD30F: std::string::reserve(unsigned long) (basic_string.tcc:512)
==26681== by 0x4CCD5D4: std::string::append(char const*, unsigned long) (basic_string.tcc:310)
==26681== by 0x4C86384: std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, char) (istream.cc:397)
==26681== by 0x4026ED: main (test.cpp:210)
==26681==
==26681== LEAK SUMMARY:
==26681== definitely lost: 0 bytes in 0 blocks
==26681== indirectly lost: 0 bytes in 0 blocks
==26681== possibly lost: 28 bytes in 1 blocks
==26681== still reachable: 1,728 bytes in 72 blocks
==26681== suppressed: 0 bytes in 0 blocks
==26681== Reachable blocks (those to which a pointer was found) are not shown.
==26681== To see them, rerun with: --leak-check=full --show-reachable=yes
==26681==
==26681== For counts of detected and suppressed errors, rerun with: -v
==26681== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
这是 test.cpp 的第 210 行
bool pending = getline(inputfile, line);
还有几行:
string line;
bool pending = getline(inputfile, line);
int round = readOption(inputfile);
int num = readOption(inputfile);
我认为它与 getline 失败有关,并且因为 line 是 string 它以某种方式永远不会释放该内存。我该如何防止这种情况?
readOption 也使用getline,但我认为它没有内存泄漏,因为string line 是在本地定义的,然后超出范围,有效地清理了内存?
编辑 1:
我已经通过创建一个虚拟函数“解决”了这个问题:
bool getnewline(ifstream &inputfile) {
string line;
return getline(inputfile, line);
}
但是这样做似乎很愚蠢,我不确定为什么 valgrind 会抱怨如果没有泄漏。我仍在寻求更好/更干净的解决方案。
【问题讨论】:
-
您显示的所有变量都有自动存储期限。它们不能泄漏。
-
我不知道怎么理解 valgrind 的抱怨
-
我今天已经看到了这个(几乎)相同的问题......
-
鉴于该块“可能丢失”,它也可能“可能未丢失”,并且您的代码表明“未丢失”是正确的。我不确定我是否会相信这两种分析,但这就是表面上的意思。我建议查看其他三个损失记录,并在可能的情况下修复这些记录。您最终可能会创建一个抑制 - 但要谨慎这样做。您需要通过运行许多使用
getline()并报告基本相同的“可能丢失”错误的程序来验证它是否有必要。如果只有这个程序触发了错误,那很可能是你的程序。 -
valgrind错误/警告摘要怎么说 BTW?
标签: c++ string memory-leaks valgrind getline