[英]Exception thrown: write access violation. newNode was nullptr
I'm just getting back into coding. 我只是回到编码。 It's been a few years. 已经好几年了 I can not figure out why this is throwing a nullptr access violation. 我不知道为什么这会引发nullptr访问冲突。 I've condensed it into a single line of code. 我已经将其压缩为一行代码。 The violation is thrown when I try to set my second entry (newNode's pLast pointer) to head. 当我尝试将第二个条目(newNode的pLast指针)设置为head时,将引发冲突。
I'm trying to create a doubly linked list with a bubble sort based off of searches performed (aka countVar). 我正在尝试根据执行的搜索(也称为countVar)创建带有气泡排序的双向链接列表。 Any help would be great. 任何帮助都会很棒。
#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
}
I've put comments in your code to see why you have the access violation. 我已经在您的代码中添加了注释,以查看为什么出现访问冲突。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.