valgrind& C ++:从字符缓冲区构建std :: string

时间:2011-01-01 20:53:58

标签: c++ valgrind

简单的C ++ / valgrind问题我希望有人可以提供帮助。

当针对以下代码运行valgrind时,我得到两个与std :: string相关的泄漏:

==10325== 17 bytes in 1 blocks are possibly lost in loss record 1 of 2
==10325==    at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==10325==    by 0x40CFD05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0B10: ??? (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0CF5: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x804872B: main (test.cc:9)
==10325== 
==10325== 17 bytes in 1 blocks are possibly lost in loss record 2 of 2
==10325==    at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==10325==    by 0x40CFD05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0977: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D17AC: std::string::reserve(unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D1C7F: std::string::append(std::string const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D1D63: std::string::operator+=(std::string const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x804879D: main (test.cc:11)

虽然抑制它们并不是太多的工作,而且代码对我来说似乎很简单,但我想确保在我尝试说服valgrind之前我不会错过任何明显的东西我知道什么我在做。

#include <stdio.h>
#include <stdlib.h>
#include <string>

int main(int argc, char *argv[])
{
        char buffer[8192];
        sprintf(buffer, "ABCD");
        std::string str(buffer);
        std::string str2 = "";
        str2 += str;
        exit(EXIT_SUCCESS);
}

2 个答案:

答案 0 :(得分:7)

通过调用exit()来终止程序并不是一个有序的关闭,它基本上会中止当前位置的程序。因此,strstr2在程序终止之前不会被销毁,而valgrind会在程序终止之前将其销毁。

当您从main返回时正常退出程序时,strstr2的析构函数应该被调用,报告的“内存泄漏”应该消失。

答案 1 :(得分:6)

另请注意,如果您使用的是libstdc++(Linux和某些BSD的标准c ++库),则应使用GLIBCXX_FORCE_NEW编译程序,以禁用std::string内存池优化,这看起来像是泄密给了valgrind。请记住为您的发布版本转回去:-)。