char数组的内存分配

时间:2012-04-07 18:08:25

标签: c++ memory-management memory-leaks valgrind

我有以下代码:

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)

我做错了什么?

2 个答案:

答案 0 :(得分:0)

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

这不应该是:

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

答案 1 :(得分:0)

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