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?