簡體   English   中英

引發異常:寫訪問沖突。 newNode為nullptr

[英]Exception thrown: write access violation. newNode was nullptr

我只是回到編碼。 已經好幾年了 我不知道為什么這會引發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
        }

我已經在您的代碼中添加了注釋,以查看為什么出現訪問沖突。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM