Reputation: 535
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?
Upvotes: 8
Views: 2412
Reputation: 224387
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.
Upvotes: 17
Reputation: 2868
The actual reason you're getting a double free error is pinned to the fact that instead of creating a new string object for your variables a
and b
, you just copy the reference (a string
object is implemented using a variable length char *
).
Since the string
destructor frees this memory address when your program ends, and as explained above you have two string objects pointing to the same address, you get a double free error
This will work, like @JesperJuhl said, you must use a copy constructor
#include <iostream>
#include <string>
#include <cstring>
struct test
{
std::string name;
size_t id;
};
int main()
{
test t;
test a;
test b;
t.name = "147.8.179.239";
t.id = 10;
a=t;
b=t;
std::cout << b.name << " " << b.id << std::endl;
}
Upvotes: 6
Reputation: 31459
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.
Upvotes: 12