Writing a telephone
to a file as a binary blob will not work. telephone
contains name
and name is a std::string
. A std::string
does not typically contain the string data it represents; it contains a pointer to the string data.
So when you
f.write((char*)&p,sizeof(telephone));
what you actually wrote to the file was not the string data, but a pointer to the string data. This means that
f.read((char*)&q,sizeof(telephone));
reads back p
's pointer to q
and that means that p
and q
both point at the same string data. This is bad.
When p
or q
go out of scope and are destroyed, they destroy name
, and name
, like a good little std::string
, and frees the memory it points at. This leaves the other object containing a std::string
pointing at memory that has been freed, and sooner or later that other object will either be used and invoke undefined behaviour or be destroyed and attempt to free the previously freed memory. This is what is meant in the error message by "double free". The same memory has been freed twice.
In your case, if q
is deleted before p
, q
releases the memory that both p
and q
point at leaving p
pointing at an invalid memory location. A few nanoseconds later p
is deleted and p
cannot free the already freed memory.
To get around this you must ensure the contents of the std::string
are written to the file and then read back. This is called serialization.
Typical solutions to this problem are to write the data to the file in a text format with <<
and read it back with >>
(which may require you to implement the <<
and >>
operators for your class)
class telephone
{
string name;
long number;
public :
void getdata();
void display();
friend std::istream & operator<<(std::istream & out, const telephone & tp);
friend std::ostream & operator>>(std::ostream & in, telephone & tp);
};
or add serialization functions to the class
class telephone
{
string name;
long number;
public :
void getdata();
void display();
bool serialize(std::iostream & out);
bool deserialize(std::iostream & in);
};
The writing of these functions is probably the point of this assignment, so I'll stop here. Don't worry. Both are approaches are exceedingly well documented online if you have trouble. I recommend starting with the first option. It is much easier to debug because you can read the text file to see if you got it wrong.