为什么这个函数会导致崩溃?(多目表)
Why is this function causing a crash? (Multilist)
我正在做我的第一个多列表,到目前为止它一直是一个噩梦。现在,我允许用户自己放置x,y点(class_number,student_number)。我的节点看起来像这样:
typedef struct node {
int student_number;
int class_number;
struct node* classpointer;
struct node* studentpointer;
}* nodePtr;
初始化为
List::List() {
head = nullptr;
currClass = nullptr;
currStudent = nullptr;
}
为了添加数据值和设置指针,我有两个函数:
void List::addNodeToClass() {
nodePtr n = new node;
n->classpointer = NULL;
cout << "What class number would you like to add?" << endl;
int x;
cin >> x;
n->class_number = x;
if(head != NULL) {
currClass = head;
while (currClass->classpointer != NULL) {
currClass = currClass->classpointer;
}
currClass->classpointer = n;
}
else {
head = n;
}
}
和
void List::addNodeToStudent() {
nodePtr n = new node;
n->studentpointer = NULL;
cout << "What student number would you like to add?" << endl;
int x;
cin >> x;
n->student_number = x;
if(head != NULL) {
currStudent = head;
while (currStudent->studentpointer != NULL) {
currStudent = currStudent->studentpointer;
}
currStudent->studentpointer = n;
}
else {
head = n;
}
}
我在我的menu()函数中调用了这两个函数,而在main()中我只调用了menu()
int menu() {
int input;
List List;
while (input != 3) {
cout << " " << endl;
cout << "Press '1' to input a node" << endl;
cout << "Press '2' to view the list of nodes" << endl;
cout << "Press '3' to exit" << endl;
cout << " " << endl;
cin >> input;
if (input == 1) {
List.addNodeToClass();
List.addNodeToStudent();
}
else if (input == 2) {
List.PrintList();
}
else if (input == 3) {
return 0;
}
else {
cout <<"That is an invalid key" << endl;
}
}
}
当我运行程序时,我能够输入类节点,然后当我进入学生节点时,按下enter键后程序崩溃了。我知道有很多东西要看,但我不明白为什么会这样。如果有人能告诉我我在这里做错了什么,我会非常感激。谢谢你。
addNodeToClass
函数从不设置node->studentpointer
。因此,当您遵循addNodeToStudent
中的指针时,您正在解引用垃圾。
使用默认的node
构造函数会更安全:
typedef struct node {
node()
{
student_number = 0;
class_number = 0;
classpointer = nullptr;
studentpointer = nullptr;
}
int student_number;
int class_number;
struct node* classpointer;
struct node* studentpointer;
}* nodePtr;
这将解决您的问题,因为这些属性并不总是在您的代码中初始化(new node
不初始化node
属性,如果没有这样的构造函数)。
相关文章:
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- C 回调函数在对象 pascal 上崩溃
- 除非使用某些寄存器,否则函数挂钩会崩溃
- Linux c++.在预加载的共享库中定义的基类的崩溃调用函数
- Rcpp 函数在打包时使 RStudio 崩溃
- 使用 MS 绕道挂钩在调用钩子函数时崩溃C++
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 使用唯一指针调用函数会使我的程序崩溃
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- 程序在为链表创建推送函数时崩溃
- 递归导致程序崩溃,但 while 循环中的相同概念不是来自C++析构函数
- 从 C# 模块调用C++函数引发随机崩溃
- C++设置器函数崩溃
- EGL 在第一次 opengl 函数调用时崩溃
- 我需要做一个空函数循环回来,而不会让它崩溃或跳过
- 当我使用 ALSA lib 的函数"snd_pcm_readi"时它崩溃了
- 在C++中删除指针数组时析构函数崩溃
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃