对分段错误的理解不正确

Improper Understanding of Segmentation Fault

本文关键字:不正确 分段 错误      更新时间:2023-10-16

我得到了一个分段错误,从我读到的内容来看,这是由于我试图访问我不允许访问的内存的某些部分。

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

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

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

我已经创建了 3 个类型的帐户,它们存储在二进制文件帐户详细信息中.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 << "CREATEDn";
}
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()函数调整为非交互式。