链表的总线错误(核心转储)
Bus error (core dumped) with Linked Lists?
我正在编写一个程序,允许用户键入要读取的人员数据库的文件名;然后,该程序在每个状态链接中创建状态对象的链接列表和人员对象的链接列表,以组织文件中的信息。
我知道链表部分有效,因为我能够直接在文件名中编码并打印出状态列表和每个状态的人员列表;但是,当我尝试允许用户输入文件名作为命令时,我收到 Bus 错误。当我在 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*
的构造函数。 不过,在read()
函数中将参数更改为const char *filename
。
相关文章:
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 浮点异常(核心转储)#694457
- 分段错误(核心转储)但无法弄清楚
- 链接到libkcapi时没有核心转储
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 如何使用 lldb 在曼扎罗中调试 lz4 文件格式的核心转储?
- qt C++命令行代码中的分段错误(核心转储)
- 从文件中读取的数据,但发生核心转储错误
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- C++ atof - 分段错误(核心转储)
- Linux C 只禁止我的程序使用核心转储
- 为什么我的代码包含错误分段错误(核心转储)?