1

I have this code which is supposed to

  1. read data to class object from user
  2. Write that data to binary file
  3. Read data from binary file
  4. Display it to user.

int main()
{
    Bahd b;    //Bahd is a class
    cin>>b;    //overloaded insertion operator
    ofstream outfile("Data.bin",ios::out|ios::binary);
    outfile.write(reinterpret_cast<char*>(&b),sizeof(b));
    outfile.close();
    ifstream infile("Data.bin",ios::in|ios::binary);
    Bahd c;
    infile.read(reinterpret_cast<char*>(&c),sizeof(c));
    cout<<c;
}
but I get error when running the program, at the point after inputting data.
*** Error in `./a.out': munmap_chunk(): invalid pointer: 0x00007ffccbfbca50 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x71e75)[0x7fdf6d79ae75]
/usr/lib/libc.so.6(+0x777c6)[0x7fdf6d7a07c6]
./a.out[0x401280]
./a.out[0x401156]
/usr/lib/libc.so.6(__libc_start_main+0xf0)[0x7fdf6d749610]
./a.out[0x400e69]
======= Memory map: ========
**more lines here**
Aborted (core dumped)

Here is the class

    class Bahd{
    private:
        string name;
        long acc_no;
        long double bal;
    public:
        friend istream& operator >>(istream& src,Bahd& b);
        friend ostream& operator <<(ostream& dest,Bahd& b);
    };

What wrong am I doing?

Registered User
  • 2,239
  • 3
  • 32
  • 58

1 Answers1

2

You can not identity-serialize (that is, pretend you are dealing with some random bytes in memory and move those bytes around) any non-trivial class in C++. And your class has an std::string in it, which makes it non-trivial - since std::string is non-trivial.

Instead, you should proprely serialize it.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • …for example, using [Boost.Serialization](http://www.boost.org/doc/libs/1_60_0/libs/serialization/doc/index.html) – mindriot Feb 29 '16 at 14:33