对Segmentation Fault的错误理解

Improper Understanding of Segmentation Fault

我遇到了分段错误,据我所知,这是因为我试图访问我不允许访问的某些内存部分。

我几乎可以肯定我的问题出在我的 ShowAccounts 函数内的 while 循环中。

while (input.read((char *) &account, sizeof(BankAccount)))

在多次尝试理解这个 read 调用的工作原理后,我认为我没有正确理解它。

我已经创建了 3 个 BankAccount 类型的帐户,它们存储在二进制文件 AccountDetails.dat 中,但是,我无法访问它们。

如果您不能帮助我全面推理为什么我会收到此分段错误,也许您可​​以解释一下读取函数的工作原理以及它尝试执行的所有操作,然后我可以做一些更多评价?欢迎任何和所有回复。

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

class BankAccount
{
public:
    void CreateAccount();
    void ShowAccount();
private:
    int accountNumber;
    string firstName;
    string lastName;
    char accountType;
    double balance;
};

void MakeAccount();
void ShowAccounts();

int main()
{
    ShowAccounts();

    return 0;
}

void BankAccount::CreateAccount()
{
    cout << "Enter the account number.\n";
    cin >> accountNumber;
    cout << "Enter the first and last name of the account holder.\n";
    cin >> firstName >> lastName;
    cout << "What kind of account is it? S for savings or C for checking.\n";
    cin >> accountType;
    cout << "How much are you depositing into the account?\n";
    cin >> balance;
    cout << "CREATED\n";
}

void BankAccount::ShowAccount()
{
    cout << "Account Number:  " << accountNumber << endl;
    cout << "Name:  " << firstName << " " << lastName << endl;
    cout << "Account Type:  " << accountType << endl;
    cout << "Current Balance:  $" << balance << endl;
}

void MakeAccount()
{
    BankAccount account;
    ofstream output;
    output.open("AccountDetails.dat", ios::binary|ios::app);
    if (!output)
        cerr << "Failed to open file.\n";
    account.CreateAccount();
    output.write((char *) &account, sizeof(BankAccount));
    output.close();
}

void ShowAccounts()
{
    BankAccount account;
    ifstream input;
    input.open("AccountDetails.dat", ios::binary);
    if (!input)
        cerr << "Failed to open file.\n";
    while (input.read((char *) &account, sizeof(BankAccount)))
    {
        account.ShowAccount();
    }
    input.close();
}

当您尝试将输入流中的字节直接读取到包含指针或字符串的结构中时,您会将它们包含的指针设置为垃圾。 (字符数组将起作用。)尝试使用指针和字符串将导致未定义的行为,这 可能 导致发生分段错误。或者其他。

要检查这一点,请在调试器中加载程序,在该行设置断点,然后 运行。当您到达那里时,检查结构及其成员以查看它们包含的数据是否有效。

尝试将您的 BankAccount::CreateAccount() 函数调整为非交互式。