1

I'm trying to save and load a class Student using binary files. This is how the classes are:

class Student{
    char name[100];
    int regno;
    vector<Subjects> subjects;
};

class Subjects{
    char initial;
    int id;
};

I'm saving and loading this way:

void saveFile(){
    fstream f1;
    f1.open("data.bin", ios::out | ios::binary);
    f1.write((char*)&student, sizeof(Student));
    f1.close();
}

void loadFile(){
    fstream f1;
    f1.open("data.bin", ios::in | ios::binary);
    f1.read((char*)&student, sizeof(Student));
    f1.close();
}

Nothing fancy as you can see with the saving and loading, but I tested this through print statements, and it's the vector component causing a crash when running it in the terminal (cmd.exe).

Orbviox
  • 141
  • 1
  • 9
  • You can't write non-[pod](https://stackoverflow.com/questions/146452/what-are-pod-types-in-c) classes to a file like that – Alan Birtles Feb 21 '20 at 13:06
  • [This](https://stackoverflow.com/questions/51230764/serialization-deserialization-of-a-vector-of-integers-in-c) might be interesting – Jabberwocky Feb 21 '20 at 13:06
  • And while you're at it: Use `std::string Foo` instead of `char Foo[some_size]`. – Jabberwocky Feb 21 '20 at 13:09
  • Because `class Student` is not a POD object (https://stackoverflow.com/a/146454/3421515). It is better to prefer serialization/deserialization library. Such as https://github.com/USCiLab/cereal – calynr Feb 21 '20 at 13:11

2 Answers2

2

You can't simply save and load the object unless you serialze the Student object before saving it to file.

Rationale:

class Student is not a POD type. std::vector<Subjects> in your Student class simply holds a pointer to the underlying memory which holds Subjects, since vector uses heap to hold its contents. When you save the object to a file, you simply save the pointer along with the Student object, but not the actual data. Therefore when you try to recreate the same object from the saved binary data, you simply have access to a memory address not the actual content.

In C++ world, boost::serialization, Protocol buffers and cereal are most known (but not limited to) serialization libraries to achieve what you're trying to do.

aep
  • 1,583
  • 10
  • 18
0

std::vector is not a POD type.

std::vector allocated dynamic memory and stores pointer somewhere internally. When you write it to file, you just write a header to that dynamic memory, which is std::vector. When you read it again, it is not a valid pointer anymore, and you get crash.

Tarek Dakhran
  • 2,021
  • 11
  • 21