0

我有以下代码:

Document document;
char *buf = new char[str.size()+1];
buf[str.size()] = '\0';
memcpy(buf, str.c_str(), str.size());
//string parsing
if (document.ParseInsitu<0>(buf).HasParseError()) {
    cerr << "Failed to parse string ";
}
delete[] buf;

当我用 valgrind 检查程序时,我得到了这个:

==29765== Invalid read of size 1
==29765==    at 0x402A682: bcmp (mc_replace_strmem.c:679)
==29765==  Address 0x49626a2 is 2 bytes inside a block of size 214 free'd
==29765==    at 0x402759B: operator delete[](void*) (vg_replace_malloc.c:409)

==29765== Invalid read of size 1
==29765==    at 0x402901A: strlen (mc_replace_strmem.c:282)
==29765==    by 0x41ABE4A: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==29765==  Address 0x49626a8 is 8 bytes inside a block of size 214 free'd
==29765==    at 0x402759B: operator delete[](void*) (vg_replace_malloc.c:409)

==29765== Invalid read of size 1
==29765==    at 0x4029D0E: memcpy (mc_replace_strmem.c:635)
==29765==    by 0x41ABD15: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==29765==    by 0x41ABE65: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==29765==    by 0x2C23: ???
==29765==  Address 0x49626b2 is 18 bytes inside a block of size 214 free'd
==29765==    at 0x402759B: operator delete[](void*) (vg_replace_malloc.c:409)

我究竟做错了什么?

4

2 回答 2

0
buf[json.size()] = '\0';

这不应该是:

buf[str.size()] = '\0';

?

于 2012-04-07T18:11:43.147 回答
0

问题是我释放buf得太早了。我认为解析器会复制输入,这显然是错误的。

于 2012-04-08T17:18:41.720 回答