Search code examples
c++fstreamunhandled-exception

Exception thrown while reading elements from a binary file (Exception thrown: read access violation. _Pnext was 0xB414D4.)


first of all i made a simple class:

class test
{
public:
    test(string name="",int age=0);
    void getData();
    void show();
private:
    string name;
    int age;
};

test::test(string name,int age)
{
    this->age = age;
    this->name = name;
}
void test::getData()
{
    cin >> age;
    cin >> name;
}
void test::show()
{
    cout << "AGE:" << age<<"\n";
    cout << "NAME:" << name << "\n";
}

in my main function called the getData() method to input values from user and then saved them in a binary file. Now when i try to read the file, it does store the value in the new object of the class but i get an exception (Exception thrown: read access violation. _Pnext was 0xB414D4.) my main function looks like this :

int main()
{
    ifstream os("new.dat", ios::binary);
    test b;
    os.read(reinterpret_cast<char*>(&b), sizeof(b));
    b.show();
    return 0;
}

Solution

  • The issue here is that you are trying to read the test object as if it is a simple flat object. For many, many reasons, this is almost always a bad idea.

    In your case, the std::string member is not a simple object at all! Under the hood, std:: string usually has at least 1 pointer member to where it has allocated the string.

    If you simply save the stest object in one session, and restore the binary representation in another session, then you set these pointers to addresses that are now completely garbage.

    The process of saving a data structure in a way that is later recoverable is called serialisation, and is a complex subject.