program crashes in the end
Hi everyone.
Program seems to work fine, but crashes in the end, after the destructors are called. Why???
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include "Furniture.h"
#include <fstream>
using namespace std;
void main (int argc, char *argv[])
{
string FileName = "TheFurniture";
cout << argv[0] << "\nRunning" << endl;
ofstream FileOut;
FileOut.open(FileName, ios::binary);
Furniture Table ("Baroc", 78);
FileOut.write((char*) &Table, sizeof Table);
FileOut.close();
ifstream FileIn (FileName, ios::binary);
Furniture Table1 ("Ancient", 99);
Table1.getInfo();
FileIn.read((char*) &Table1, sizeof Table1);
Table1.getInfo();
FileIn.close();
|
You shouldn't write/read a class like that.
Why it actually crashes depends on the Furniture
class. If it contains virtual functions or other pointer then yes it will crash.
"You shouldn't write/read a class like that."
Please give an example of better code.
Here is the Furniture.h. No virtual functions, neither pointers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
using namespace std;
class Furniture
{
public:
Furniture() {cout << "Furniture default constructor\n";}
Furniture (string Model, int Number ):itsModel(Model),itsNumber(Number) {}
~Furniture() {cout << "Furniture default destructor\n";}
void getInfo() const;
private:
string itsModel;
int itsNumber;
};
void Furniture::getInfo() const
{
cout << "This is " << this -> itsModel << " furniture\n";
cout << "It's Number is " << this -> itsNumber << endl;
}
|
not obvious, but there is.
string
uses pointer.
Please give an example of better code. |
Use the stream operators. Like so:
out:
FileOut << Table.itsModel << " " << Table.itsNumber;
in:
FileIn >> Table.itsModel >> Table.itsNumber;
Thanks for the example.
if string
uses pointer, I should delete it ?
As I understand, this creates a memory leak and causes the program to crash.
No, you should delete anything that you created using
new
. Do not delete something just because you've got a pointer to it.
Topic archived. No new replies allowed.