Johnnylin Johnnylin - 2 months ago 15
C++ Question

double free or corruption error when copying object with memcpy

I have the following code:

#include <iostream>
#include <string>
#include <cstring>

struct test {
std::string name;
size_t id;

int main() {
test t; = ""; = 10;

char a[sizeof(t)] = "";
std::memcpy(a, &t, sizeof(t));

test b;
std::memcpy(&b, a, sizeof(t));

std::cout << << " " << << std::endl;

when I compile it and run it, it gives me the following error: 10
*** Error in `./test': double free or corruption (fasttop): 0x0000000000bf9c20 ***
Aborted (core dumped)

It turns out the code can print out the result. But how can I fix this error?


By using memcpy the way you are, you have two std::string objects which are exactly identical. This includes any pointers they may use internally. So when the destructor for each object runs, they are both attempting to free the same pointer.

This is why you need to use either the copy constructor or assign one to the other (i.e. use the overridden operator=). It knows about those implementation differences and handles them correctly, i.e. it allocates a separate memory buffer for the destination object.

If you want to extract the string contained in a std::string, you need to serialize the object to a known representation. Then you can deserialize it to convert it back.

std::string s1 = "hello";
printf("len=%zu, str=%s\n",s1.size(),s1.c_str());

// serialize
char *c = new char[s1.size()+1];
strcpy(c, s1.c_str());

// deserialize
std::string s2 = c;
printf("len=%zu, str=%s\n",s2.size(),s2.c_str());

You would perform similar steps for other class objects.