c++ - 抛出异常 : write access violation. newNode 为 nullptr

标签 c++ pointers exception error-handling nullpointerexception

我刚刚重新开始编码。已经有几年了。我不明白为什么会引发 nullptr 访问冲突。我把它压缩成一行代码。当我尝试将我的第二个条目(newNode 的 pLast 指针)设置为 head 时,会引发违规。

我正在尝试创建一个双向链表,并根据执行的搜索(又名 countVar)进行冒泡排序。任何帮助都会很棒。

#include <iostream>
#include <stdlib.h>

using namespace std;

//build class that has a private function to inc count. 
class LinkedListCount {
private:
    struct CountNode {
        int data;
        int countVar; //Make the variable "countVar" private to protect integrity. 
        CountNode* pNext = NULL;
        CountNode* pLast = NULL; //Needed for bubbling back through list. 

    };
    //Keep track of head
    CountNode* head;
    CountNode* current;
    CountNode* temp;



public:
    //Constructor Function (Set default values for head, current, and temp) 
    LinkedListCount() {
        head = NULL;
        current = NULL;
        temp = NULL;
    }
    void AddNode(int dataIn) { //Addnode Function
        //Create and populate list. 
        CountNode* newNode = new CountNode; 
        newNode->pNext = NULL; 
        newNode->pLast = NULL;
        newNode->data = dataIn;
        temp = head;
        newNode->countVar = 0;
        if (temp != NULL) { //We already have data entery.
            if (temp->pNext == NULL) {
                newNode = temp->pNext;
                newNode->pLast = head; //****THIS IS WHERE ACCESS VIOLATION OCCURES
            }
            //Set variables with the understanding that the head is the only data point. 
            else {
                current = temp->pNext; //Set it equal to head. 
            }
            while (current->pNext != NULL) {//This could be eliminated with keeping track of a tail. 
                current = current->pNext; //Attach this to the end of the list. 
            }
            current->pNext = newNode; //And newMode->pNext = to Null so next time I add data I'll get to the end of the list. 
            newNode->pLast = current;
        }
        else if (head == NULL) {
            head = newNode;
        }

    }
};

void addNodes(LinkedListCount &DataList) { //Populates list. 

    for (int i = 0; i < 20; i++) {
        DataList.AddNode(i);
    }
}



int main(void)
{       
addNodes(DataList);   
}

最佳答案

            if (temp->pNext == NULL) { // temp->pNext is NULL
            newNode = temp->pNext; // newNode is now NULL too
            newNode->pLast = head; // attempt to use pLast of NULL
        }

我已经在您的代码中添加了注释,以查看您出现访问冲突的原因。

关于c++ - 抛出异常 : write access violation. newNode 为 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933050/

相关文章:

对指针的更改不是永久性的

c# - 收藏已修改;枚举操作可能不会执行随机弹出 - HTTP?

c++ - 为什么我的 Threaded Thrift 调用速度很慢?

c++ - 抓老鼠?

C++ 地址处理(指针)

c - 结构在其他文件的可见性方面如何表现?

Python:必须导入非内置异常才能捕获它们吗?

java - 如果在 EDT 线程之外调用 AWT 代码,如何引发异常?

c++ - 三次调用函数后可执行文件崩溃

java - 单作者多读者原语图