2016-03-08 59 views
0
==3275== Invalid read of size 8 
==3275== at 0x53D006E: [email protected]@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) 

這是相關代碼:我不明白一個Valgrind的錯誤我得到

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

哪裏特點是擁有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

誰或什麼管理'msg'指向的數據的生命週期?看起來你已經搞砸了。構建「UTF8err」的代碼在哪裏? –

+0

@DavidSchwartz我只是在'string range =「:invalid range」;'然後'把UTF8err(range.c_str());'放到main中。 – user

+0

那顯然是行不通的。 –

回答

1

當你調用c_str,其結果是有效的,只要該字符串沒有被修改或破壞。但是當你扔掉時,堆棧被解開,破壞了字符串。所以指針指向不再存在的東西。

也許將msg的類型從const char*更改爲std::string。也許使字符串static。也許讓UTF8err類管理自己的內存。

相關問題