字符数组的内存分配

memory allocation of char array

本文关键字:分配 内存 数组 字符      更新时间:2023-10-16

我有以下代码:

Document document;
char *buf = new char[str.size()+1];
buf[str.size()] = '';
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)

我做错了什么?

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

这不是应该是:

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

问题是我过早地解除了buf。我认为解析器将复制输入,这显然是错误的。