I have the following code:
#include <iostream>
#include <string>
#include <cstring>
struct test {
std::string name;
size_t id;
};
int main() {
test t;
t.name = "147.8.179.239";
t.id = 10;
char a[sizeof(t)] = "";
std::memcpy(a, &t, sizeof(t));
test b;
std::memcpy(&b, a, sizeof(t));
std::cout << b.name << " " << b.id << std::endl;
}
when I compile it and run it, it gives me the following error:
147.8.179.239 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());
printf("c=%s\n",c);
// 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.
You cannot memcpy()
a non-POD struct like test
. You are completely wrecking the std::string
member.
You must use the copy constructor to copy C++ objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With