【问题标题】:Interpreting Valgrind Memory Leak Summary Log解释 Valgrind 内存泄漏摘要日志
【发布时间】:2014-10-28 09:41:11
【问题描述】:

我正在使用 Valgrind(一种内存泄漏工具)来查找潜在的内存泄漏。它是这样运行的:

$ valgrind --leak-check=full ./myApp

报告如下:

==9458== 15,007 bytes in 126 blocks are possibly lost in loss record 622 of 622
==9458==    at 0x4029FDE: operator new(unsigned int) (vg_replace_malloc.c:313)
==9458==    by 0x415F213: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19)
==9458==    by 0x4161125: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19)
==9458==    by 0x41617AF: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19)
==9458==    by 0x808B061: Parser::parseLinear(rapidxml::xml_node<char>*, Linear*) (Parser.cpp:663)

==9458== 
==9458== LEAK SUMMARY:
==9458==    definitely lost: 0 bytes in 0 blocks
==9458==    indirectly lost: 0 bytes in 0 blocks
==9458==      possibly lost: 20,747 bytes in 257 blocks
==9458==    still reachable: 57,052 bytes in 3,203 blocks
==9458==         suppressed: 0 bytes in 0 blocks
==9458== Reachable blocks (those to which a pointer was found) are not shown.
==9458== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==9458== 
==9458== For counts of detected and suppressed errors, rerun with: -v
==9458== ERROR SUMMARY: 21 errors from 21 contexts (suppressed: 0 from 0)

根据摘要,似乎存在“可能丢失”的内存泄漏。但是,在 Parser.cpp 中跟踪第 663 行后,我似乎无法确定问题所在。 xml_node* 是开源库 RapidXML 的一部分。源代码如下所示:

line 661: Tracker track;
line 662: xml_node<>* trackingNode = node->first_node(); // rapidxml API
line 663: track.setValue(trackingNode->first_node()->value());

其中 setValue 定义为:

void Tracker::setValue(const string& s) {
    this->val = s;
}

【问题讨论】:

  • setValue() 是否内联? valstring 吗?
  • 嗨 jxh,是的 val 是一个字符串。 setValue 实际上是一个类的成员函数。它应该看起来像: void myClass::setValue(const string& s)
  • 是在类的头文件中定义setValue()方法,还是显式声明inline,或者在第663行时定义在其源代码体已经被编译器解析的地方正在编译?我想知道函数调用是否被内联。
  • 此外,xml_node* 是名为 RapidXML 的开源库的一部分。 first_node() api 记录在这里:rapidxml.sourceforge.net/…
  • @jxh,setValue() 方法定义在类头文件之外的 .cpp 文件中,未声明为内联

标签: c++ memory memory-leaks valgrind


【解决方案1】:

根据rapidxml manualxml_base::value() 不会使用rapidxml::parse_no_string_terminators 选项返回以零结尾的字符串。

如果设置了此选项,则根据xml_base::value_size() 终止您的字符串。

另外,在调用 xml_base::value() 之前检查值是否不为空。在其他情况下 value() 返回可能是另一个内存泄漏问题的空字符串。

【讨论】:

  • 获取字符串的长度如何终止?
  • 例如:if (trackingNode->first_node()->value_size()) track.setValue(string().append(trackingNode->first_node()->value(), trackingNode->first_node ()->value_size());
  • 编辑后会更好。顺便说一句,string 有一个演员可以做到这一点:不需要append
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 2020-03-31
相关资源
最近更新 更多