I have the following struct
typedef struct a_t
{
vector <int> a;
int p;
}a;
typedef struct b_t
{
a x;
int y;
}b;
struct a is a struct contain a vector,struct b contain struct a I wanna write/read the struct b into a binary file. The following code doesn't work
int main()
{
b m;
m.x.a.push_back(1);
m.x.a.push_back(2);
m.x.a.push_back(3);
m.x.p = 5;
m.y = 7;
cout << sizeof(m.y) << endl;
cout << sizeof(m.x) << endl;
cout << sizeof(m) << endl;
ofstream outfile("model",ios::out|ios::binary);
outfile.write((char*)&m,sizeof(m));
outfile.close();
b p;
ifstream iffile("model", ios::in|ios::binary);
iffile.read((char*)&p,sizeof(a));
iffile.close();
cout << p.y << endl;;
cout << p.x.p << endl;
cout << p.x.a[0] << endl;
cout << p.x.a[1] << endl;
cout << p.x.a[2] << endl;
return 0;
}
The error message is "* glibc detected double free or corruption (top): 0x0000000000504010 ** Aborted (core dumped)" beside,it does't write the struct into the file.
std::arraytostd::vector.std::vectormanages dynamically allocated memory, whilestd::arraydoesn't. In this case, it would make the naive method of accomplishing this (cast to/from char* and write/read) work.