Valgrind内存泄漏与std :: map中的std :: string

时间:2014-06-27 16:55:30

标签: c++ valgrind stdstring stdmap

以下是Valgrind的输出:

==6519==    at 0x4C25885: operator new(unsigned long) (vg_replace_malloc.c:319)
==6519==    by 0x4EE65D8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (new_allocator.h:104)
==6519==    by 0x4EE7CE0: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (basic_string.tcc:138)
==6519==    by 0x4EE80F7: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (basic_string.h:1725)
==6519==    by 0x41C399: pilInpOpts::pilInpOpts() (pilInpOpts.cpp:12)
==6519==    by 0x403A55: main (main.cpp:32)

对地图中的每个条目重复同样的错误。

main.cpp第32行是:

    pilInpOpts input;

pilInpOpts的第12行是构造函数的一部分:

#include "pilInpOpts.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>


pilInpOpts::pilInpOpts() 
{
// create the map of options, put in alphabetical order to ease sorting
piloptmap.insert(std::pair<std::string, bool>("bforce",false));
piloptmap.insert(std::pair<std::string, bool>("coef",false));
piloptmap.insert(std::pair<std::string, bool>("dualjet",false));
piloptmap.insert(std::pair<std::string, bool>("flow",false));
piloptmap.insert(std::pair<std::string, bool>("gforce",false));
piloptmap.insert(std::pair<std::string, bool>("gpress",false));
piloptmap.insert(std::pair<std::string, bool>("matlab",false));
piloptmap.insert(std::pair<std::string, bool>("model",false));
piloptmap.insert(std::pair<std::string, bool>("out_shade",false));
piloptmap.insert(std::pair<std::string, bool>("out_shade_file",false));
piloptmap.insert(std::pair<std::string, bool>("press",false));
piloptmap.insert(std::pair<std::string, bool>("proc",false));
piloptmap.insert(std::pair<std::string, bool>("shade",false));
piloptmap.insert(std::pair<std::string, bool>("summary",false));
piloptmap.insert(std::pair<std::string, bool>("trans",false));
// need to define the default filepaths, this is needed because they are optional
platpath = "";
vehpath = "";
apppath = "";
dockpath = "";
};

我在SO中发现了一些帖子,说Valgrind可能会产生误报。例如:std::string memory leak

这是误报,因为std :: string有所有构造函数等需要这样做吗?或者我应该更改为在地图中使用C字符数组?

2 个答案:

答案 0 :(得分:5)

此行为的一个可能原因可能是C ++标准库实现中的内存池。

来自Valgrind faq

  

很多破坏对象的内存不是立即存在的   释放并返回操作系统,但保留在池中供以后使用   再利用。事实上池没有在出口处释放   程序导致Valgrind报告此内存仍然可以访问。该   不要在出口处释放池的行为可以被称为错误   但是,图书馆。

您可以在运行应用程序之前设置GLIBCXX_FORCE_NEW环境变量,以强制STL尽快释放内存。

有关libstdc ++内存分配器实现的详细信息,请参阅这些链接:

答案 1 :(得分:1)

我对字符串有类似的问题,如果我没记错的话,我能够通过专门为容器类实现析构函数来摆脱错误。对于地图,您需要创建一个迭代器,然后在循环内显式删除iterator-&gt;元素和iterator-&gt;元素的元素。

相关问题