简体   繁体   中英

memory allocation of char array

I have following code:

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;

When I check the program with valgrind I get this:

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

what am I doing wrong?

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

isn't this supposed to be:

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

?

The problem was that I was deallocating buf too early. I supposed that the parser will make a copy of the input, which was obviously wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM