【发布时间】:2011-11-09 04:56:02
【问题描述】:
我很担心,因为我写了一个小应用程序,如果我相信 valgrind 似乎有内存泄漏(我实际上做了什么):
==9321== 251 bytes in 7 blocks are definitely lost in loss record 1 of 1
==9321== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==9321== by 0x40D3D05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==9321== by 0x40D4977: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==9321== by 0x40D57AC: std::string::reserve(unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==9321== by 0x40D5EE6: std::string::operator+=(char) (in /usr/lib/libstdc++.so.6.0.13)
==9321== by 0x804E113: xl2::TextParser::getNextLfLine() (TextParser.cpp:162)
==9321== by 0x804BFD5: xl2::UsbTree::parseStringInfo(xl2::TextParser&, std::string&, std::string&) (UsbTree.cpp:362)
==9321== by 0x804B881: xl2::UsbTree::parseDevicesFile(std::string) (UsbTree.cpp:204)
==9321== by 0x804B34E: xl2::UsbTree::updateTree() (UsbTree.cpp:70)
==9321== by 0x804E2E4: scan(std::string) (testUsbTree.cpp:75)
==9321== by 0x804E6CC: executeCommand(std::string) (testUsbTree.cpp:132)
==9321== by 0x804E8F6: hushLoop() (testUsbTree.cpp:153)
这是有问题的功能:
/**
* Returns the next line separated by UNIX style LF
* @return The next line separated by UNIX style LF
*/
std::string TextParser::getNextLfLine()
{
std::string line; // The builded line
while(this->hasMoreToken())
{
line += this->m_pText[this->m_iTokenLocation++];
// Check if we have just seen a CR/LF character
if(this->m_pText[this->m_iTokenLocation - 1] == '\n')
return line;
}
return line;
}
程序通过离开主函数正确终止(不调用 exit())。
我只是不明白为什么会出现内存泄漏。由于我的字符串被复制到堆栈中,并且应该在离开函数时清除原始字符串,对吗?或者错误可能更高?在顶层,我还将返回的值分配给一个局部变量,然后将其作为字段放入对象中(通过复制)...
所以我想知道泄漏是来自标准库还是来自 valgrind,这真的很令人惊讶!
非常感谢任何指向未泄漏内存的指针:-p!
【问题讨论】:
-
实际上我有一个内存泄漏,因为我忘记声明一个虚拟基类的析构函数,然后运行 valgrind 向我展示了一个完美的内存无泄漏应用程序!道德:除非你真的知道自己在做什么,否则无论如何都要担心 STL 内存泄漏!
标签: c++ string stl memory-leaks valgrind