gpt4 book ai didi

c++ - 我不明白我遇到的 valgrind 错误

转载 作者:行者123 更新时间:2023-11-28 05:47:53 24 4
gpt4 key购买 nike

==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;

其中字符是一个包含 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";

最佳答案

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

也许将 msg 的类型从 const char* 更改为 std::string。也许使字符串 static。也许让 UTF8err 类管理它自己的内存。

关于c++ - 我不明白我遇到的 valgrind 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com