我不明白我得到的一个valgrind错误

时间:2016-03-08 00:09:46

标签: c++ memory valgrind

==3275== Invalid read of size 8
==3275==    at 0x53D006E: _IO_file_xsputn@@GLIBC_2.2.5 (fileops.c:1362)
==3275==    by 0x53C5C6C: fwrite (iofwrite.c:45)
==3275==    by 0x4EE4C9D: std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==3275==    by 0x4EE4FA6: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==3275==    by 0x401D4C: main (q2.cc:45)
==3275==  Address 0x5a254b8 is 24 bytes inside a block of size 43 free'd
==3275==    at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3275==    by 0x4EF27BF: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==3275==    by 0x40197D: read(std::istream&, character&) (utf8char.cc:16)
==3275==    by 0x401B6C: main (q2.cc:27)

这是相关代码:

infile = new ifstream(argv[1]);
character CurrChar;
character &UTF = CurrChar;

其中character是一个包含4个字节的结构。我不认为这是相关的。

q2.cc:27 utfchar = read(*infile, UTF)

q2.cc:44   catch (UTF8err err) {
q2.cc:45         cout << err.msg << ends;
q2.cc:46         ....

其中错误是:

struct UTF8err {              // exception
  const char *msg;`
  UTF8err( const char *msg ) : msg( msg ) {}
};

utf8char.cc:16 string pad = " : invalid padding";

1 个答案:

答案 0 :(得分:1)

当您致电c_str时,只要字符串未被修改或销毁,结果就会有效。但是当你抛出时,堆栈被解开,破坏了字符串。所以指针指向不再存在的东西。

或许将msg的类型从const char*更改为std::string。也许制作字符串static。也许让UTF8err类管理自己的记忆。