You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++直接读写类对象至文件后程序崩溃的原因咨询

C++对象文件读写崩溃原因及修复方案

崩溃核心原因

你的程序直接通过write((char*)&Ahmed, sizeof(Ahmed))和read((char*)&Khaled, sizeof(Khaled))做二进制对象读写,但person类中的std::string成员本质是指针+长度+容量的结构体,并非直接存储字符串内容:

  • 写入文件时,你保存的只是std::string内部指针的内存地址,而非实际的字符串(比如"Aya"、"Badr"这些内容)。
  • 读取时,这个指针地址在当前进程空间中是无效的(要么不属于当前进程,要么对应内存已被释放),当你尝试输出Khaled.wife时,程序会通过无效指针访问内存,触发非法内存访问错误,直接崩溃。

另外,原代码中文件打开失败后没有终止后续操作,即使new_file.fail()为真,依然会执行write,这也可能引发额外错误。

修复方案

要正确存储和恢复包含std::string的类对象,需要序列化每个成员,而非直接读写整个对象:

修正后的完整代码

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class person{
public:
    string wife, son, mother;
    int brothers_num, sisters_num;
};

int main()
{
    person Ahmed;
    Ahmed.wife = "Aya";
    Ahmed.son = "Badr";
    Ahmed.mother = "Fatma";
    Ahmed.brothers_num = 2;
    Ahmed.sisters_num = 2;

    fstream new_file;
    new_file.open("database.txt", ios::out);
    if(new_file.fail()){
        cout << "无法打开文件" << endl;
        return 1; // 打开失败直接退出,避免后续无效操作
    }
    // 逐个序列化成员到文件
    new_file << Ahmed.wife << endl;
    new_file << Ahmed.son << endl;
    new_file << Ahmed.mother << endl;
    new_file << Ahmed.brothers_num << endl;
    new_file << Ahmed.sisters_num << endl;
    new_file.close();

    person Khaled;
    new_file.open("database.txt", ios::in);
    if(new_file.fail()){
        cout << "无法打开文件" << endl;
        return 1;
    }
    // 逐个从文件恢复成员
    new_file >> Khaled.wife;
    new_file >> Khaled.son;
    new_file >> Khaled.mother;
    new_file >> Khaled.brothers_num;
    new_file >> Khaled.sisters_num;
    new_file.close();

    cout << Khaled.wife << endl;

    return 0;
}

关键说明

  • 对于包含非POD类型(比如std::string、动态分配内存的成员)的类,不能直接二进制读写整个对象,必须手动序列化每个成员。
  • 如果需要更严谨的序列化,可以为类添加专门的serialize和deserialize成员函数,统一处理读写逻辑。

内容的提问来源于stack exchange,提问作者Ahmed Farag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:01:14