gpt4 book ai didi

c++ - 链接列表的总线错误(核心转储)?

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:14 25 4
gpt4 key购买 nike

我正在编写一个程序,允许用户输入要读取的个人数据库的文件名;该程序然后在每个状态链接中创建状态对象的链接列表和人员对象的链接列表,以组织文件中的信息。

我知道链表部分是有效的,因为我能够直接在文件名中编码并打印出州列表和每个州的人员列表;但是,当我尝试允许用户将文件名作为命令键入时,出现了总线错误。当我在 gdb 中运行代码时,它只告诉我:

Program received signal SIGBUS, Bus error.
0x280df0bd in std::operator>><char, std::char_traits<char> > ()
from /usr/lib/libstdc++.so.5

我什至没有得到行号!任何帮助将不胜感激。这是我的代码的命令和读取部分:

List<State*>* read(char* filename) {
string fname, lname, birthday, state;
int ssn;
List<State*>* state_list = new List<State*>();

ifstream file(filename);
if (file.fail()) {
cerr << "Error reading file.\n";
exit(1);
}

while (!file.eof()) {
file >> birthday >> ssn >> fname >> lname >> state;
Link<State*>* searchres = searchList(state, state_list);
Person* p = new Person(fname, lname, ssn, birthday, state);
if (searchres == NULL) // create new state
{
State* addedstate = state_list->addLink(new State(state))->data;
addedstate->res_list.addLink(p);
}

else // add to pre-existing state
{
searchres->data->res_list.addLink(p);
}
}
return state_list;
}

void main() {
string cmd;
cout << "Type your command in all lowercase letters.\n";
cin >> cmd;
if (cmd == "read") {
char* filnm;
cin >> filnm;
List<State*>* state_ls = read(filnm);
Link<Person*>* counter = state_ls->first->data->res_list.first;
while (counter != NULL) {
cout << counter->data->ssn << "\n";
counter = counter->next;
}
}
}

最佳答案

马上,你有一个问题:

char* filnm;
cin >> filnm;

指针未初始化,但您使用该指针读取信息。

要么使用std::string ,或适当大小的字符数组。

使用 std::string在打开的文件中:

std::string filnm;
cin >> filnm;
read(filnm.c_str());

你的 read函数还应将参数更改为 const char*而不是 char * .您没有更改传递的字符数组的内容,因此它应该是 const .

编辑:您实际上不需要使用 c_str() , 作为 std::string有一个接受 const char* 的构造函数.不过,将参数更改为 const char *filenameread()功能。

关于c++ - 链接列表的总线错误(核心转储)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29685272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com