【问题标题】:Segmentation fault when accessing a structure访问结构时出现分段错误
【发布时间】:2014-05-31 15:59:59
【问题描述】:

程序一直运行,直到它检查用户输入的名称。当您输入您希望在从充满客户信息的文件中导入的结构数组中搜索的名称时,它会返回分段错误核心转储。这让我很困惑。

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

struct AccountsDataBase{

        char name[50];
        string email;
        long int phone;
        string address;
};


#define MAX 80

AccountsDataBase * account = new AccountsDataBase[MAX];


void readIn(ifstream& file){
        int i=0;
        while(!file.eof()){
                file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
        }
}

void getAccount(){

        char userPick[50];
        char streamName[50];

        cout << " What account will we  be using? " << endl;

        cin.getline(streamName, 50);

        for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
                if( strcmp(account[i].name, streamName)==0){
                        cout << "\n\n FOUND IT!! \n\n";
                        cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
                }
        }
}

int main(){
        ifstream file;
        file.open("2.dat"); //opens data account records text
        readIn(file);
        getAccount();
        delete account;
        return 0;
}

【问题讨论】:

  • 嗯,你先在调试器中单步调试代码了吗?
  • @colin 不需要第 # 行,除非您的错误指示特定行
  • @OldProgrammer 我正在使用 vim 编辑器,并给了我一个完整的内存映射以及一个说无效指针的声明,但作为一个只有一年的程序员,我对如何回溯这个十六进制一无所知# 回到我的源代码。
  • 我建议花一些时间学习调试技能。它将为您省去很多麻烦。

标签: c++ arrays segmentation-fault structure core


【解决方案1】:

您的循环不断将所有内容读入数组的初始元素:

while(!file.eof()){
    file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}  

因为i 的值永远不会增加。您可以将其转换为 for 循环,如下所示:

for (count = 0 ; count < MAX && !file.eof() ; count++) {
    file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}

请注意,我将i 更改为count

AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;

这将帮助您解决另一个问题 - 确定数组何时以 getAccount 函数结束。目前,您假设记录始终存在,因此外部循环继续进行。现在你有了count,你可以像这样改变循环:

for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
    if( strcmp(account[i].name, streamName)==0){
        cout << "\n\n FOUND IT!! \n\n";
        cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
        break;
    }
}
if (i == count) {
    cout << "Not found." << endl;
}

【讨论】:

  • 谢谢你的第一个答案是我的一个愚蠢的错误。第二部分超出了我的知识范围,不知道如何解决这个问题,但是它给出了一种全新的分段错误,因为我更新了循环并正在打印整个内存映射
  • @ColinRickels 看看编辑,它应该让您更容易发现新的段错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 2020-05-14
  • 2020-02-06
  • 2021-11-08
  • 1970-01-01
相关资源
最近更新 更多