c++ - Why does this cpp program fail? -
note: while debugging, found until last line, program run normally, when going last bracket, mistake window pop up. i'm not quite familiar c++ couldn't locate problem. please help!
#include <iostream> #include <fstream> #include <vector> using namespace std; class test { public: int x; void add_list(int); void display(); private: vector<int> list; }; void test::add_list(int op) { list.push_back(op); } void test::display() { cout << x << endl; (unsigned int i=0;i<list.size(); i++) cout << "->" << list[i]; cout << endl; } int main (void) { test test1; test1.x = 3; test1.add_list(2); test1.add_list(4); int size = sizeof (test1); ofstream fout ("data.dat", ios_base::binary); fout.write((char *)&test1, size); fout.close(); ifstream fin ("data.dat", ios_base::binary); test test2; fin.read((char *)&test2, size); test2.display(); fin.close(); return 0; }
these lines
fout.write((char *)&test1, size);
and
fin.read((char *)&test2, size);
won't work because test
class contains objects contain pointers. std::list
allocated memory using new
store items pushed on it. keep pointers items. when write object disk, still contain pointers memory. when load object again, pointers contain same value, program may not have same memory allocated , won't have allocated object.
in case test2
appears work because internal pointers end being same test1
, when program finishes, test1
destructor releases memory allocated, test2
destructor tries release same memory, leading error.
to fix it, should change code write object in defined format doesn't use pointers (e.g. write out item count followed each items integer value). read them in same way. 1 simple fwrite won't able it.
Comments
Post a Comment