为什么这个函数会导致崩溃?(多目表)

Why is this function causing a crash? (Multilist)

本文关键字:崩溃 函数 为什么      更新时间:2023-10-16

我正在做我的第一个多列表,到目前为止它一直是一个噩梦。现在,我允许用户自己放置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属性,如果没有这样的构造函数)。