K
K
Kranj12020-12-14 22:14:02
C++ / C#
Kranj1, 2020-12-14 22:14:02

What causes a Segmentation fault (core dumped) error?

There is a class

class Car
    {
        public:
        Car()
        {
            std::string Availability = "None";
            std::string brand = "";
            int carAge = 0;

        };
        Car( const std::string &avail, const std::string &brand, int carAge)

        {

            Availability = avail;
            this->brand = brand;
            this->carAge = carAge;

        };

        void Print()
        {
            std::cout << Availability << std::endl;
            std::cout << brand << std::endl;
            std::cout << carAge << std::endl;
        }

private:
         std::string Availability;
         std::string brand;
         int carAge;

    };


Here is the program itself:
int main()
     {

         std::string path = "flash.txt";
         Car newcar("Yes", "Porsche", 5);
        std::ofstream fout;
        fout.open(path, std::ofstream::app);
        if (!fout.is_open())
        {
                std::cout << "Ошибка. Не удалось открыть файл" << std::endl;
        }
        else
        {
            std::cout << "Удалось открыть файл. Операция успешна" << std::endl;
            fout.write((char*)&newcar, sizeof(Car));
        }
        fout.close(); 

        
        std::string path = "flash.txt";
        std::ifstream fin;
        fin.open(path);
        if (!fin.is_open())
        {
            std::cout << "Не открылся файл"<< std::endl;
        }
        else
        {
            std::cout << "Файл открылся" << std::endl;
            Car machine;
           while (fin.read((char*)&machine, sizeof(Car)))
            {
                machine.Print();
            }
            
            
        }
        fin.close();
        
     }


gives a Segmentation fault (core dumped) error. Googled. Debajeel. An error occurs while running the print method. I've been breaking my head for an hour, but I'm still a beginner, I don't know what to do with it. What is the reason for this error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-12-14
@Kranj1

gives a Segmentation fault (core dumped) error.
What is the reason for this error?
class Car
    {
         ...
private:
         std::string Availability;
         std::string brand;
         int carAge;
    };
...
Car machine;
while (fin.read((char*)&machine, sizeof(Car)))

The fact that it is impossible to write complex objects to a file and read from a file in this way. This is how you can handle objects that contain their data in a contiguous chunk of memory. std::string is not one of those object classes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question