对分段错误的理解不正确
Improper Understanding of Segmentation Fault
我得到了一个分段错误,从我读到的内容来看,这是由于我试图访问我不允许访问的内存的某些部分。
我几乎可以肯定我的问题出现在我的 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()
函数调整为非交互式。
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- atoi() 在应用于大型命令行参数时会产生不正确的值
- 对分段错误的理解不正确