首页 > 解决方案 > 程序第一次运行完美,但第二次从二进制文件中读取类时想知道 seg 错误?

问题描述

我遇到的问题是程序第一次运行良好,但第二次出现段错误。一个区别是第一次创建二进制文件和第二次将数据附加到二进制文件。

#include <iostream>
#include <vector>
#include <fstream>

//count of the number of car classes written to bin file
int num_of_cars_written;
// This will be the class written to binary
class Car{
    public:
    std::string model;
    int num_of_wheels;
    std::vector<std::string> list_of_features;
    Car(std::string model, int num_of_wheels){
        this->model = model;
        this->num_of_wheels = num_of_wheels;
    }
    Car(){
        this->model = "";
        this->num_of_wheels = 0;
    }
};

void write_to_binary_file(Car& car){
    std::fstream ofile("cars.bin", std::ios::binary | std::ios::app | std::ios::out);
    ofile.write(reinterpret_cast<char*>(&car), sizeof(Car));
    ofile.close();
    ++num_of_cars_written;
}

std::vector<Car> read_bin_of_cars(std::string bin_file_path){
    std::vector<Car> car_list;
    std::fstream file(bin_file_path, std::ios::binary | std::ios::in);
    int size_of_file = sizeof(file);
    int number_of_cars_read_so_far = 0;
    Car* car;
    while(!file.eof()){
        file.read (reinterpret_cast<char*>(car), sizeof(Car));
        car_list.push_back(*car);
        number_of_cars_read_so_far += size_of_file / num_of_cars_written;
        if(number_of_cars_read_so_far >= size_of_file) break;
    }
    file.close();
    return car_list;
}

int main(){
    Car car_one("mazda", 4);
    car_one.list_of_features.push_back("cup holder");
    car_one.list_of_features.push_back("gps");
    Car car_two("honda", 4);
    Car car_three("sazuki", 2);
    car_three.list_of_features.push_back("leather seat");
    write_to_binary_file(car_one);
    write_to_binary_file(car_two);
    write_to_binary_file(car_three);
    std::vector<Car> list = read_bin_of_cars("cars.bin");
    for(auto car : list){
        std::cout << "**************Car Object**************\n";
        std::cout << car.model << std::endl;
        std::cout << car.num_of_wheels << std::endl;
        for (auto feature : car.list_of_features) {
            std::cout << feature << std::endl;
        };
    }
    return 0;
}

这是第一次运行的结果

**************Car Object**************
mazda
4
cup holder
gps
**************Car Object**************
honda
4
**************Car Object**************
sazuki
2
leather seat

这是第二次运行的结果

Segmentation fault (core dumped) (obviously)

编辑:第一次尝试的工作是未定义的行为,不应该工作。评论中列出了更好的方法来写入和读取二进制文件。

标签: c++classbinaryfiles

解决方案


此代码存在多个问题。总结几点:

write_to_binary_file

write(reinterpret_cast<char*>(&car), sizeof(Car)); 这是将对象写入文件的错误方式。它只会写对象的内存博客,car不一定会处理指向它外部分配的成员(例如stringvector等不是静态数组。它们很可能在对象之外分配内存。阅读有关序列化并利用而是它。

read_bin_of_cars

您正在读取指针car而不为其分配内存。同样,即使在分配内存之后,也要确保使用序列化从文件中读取对象。

注意你reinterpret_cast是最危险的。只有当您知道自己在做什么时,您才应该使用它。将对象直接投射到字符指针是错误的。

代码可能还有其他问题。这些只是我一眼就发现的。


推荐阅读