错误 : 异常 : 引发未处理的异常: 读取访问冲突.0xDDDDDDDD临时温度

error : exception : Unhandled exception thrown: read access violation. temp was 0xDDDDDDDD

本文关键字:异常 0xDDDDDDDD 温度 访问冲突 未处理 错误 读取      更新时间:2023-10-16

我是初学者,正在研究链表。我正在尝试制作一个程序,将元素添加到列表中,更新列表,将其释放并删除。我收到一个例外:读取访问冲突。 温度0xDDDDDDDD。 我认为 display(( 函数存在一些问题。调试器也显示相同的内容。

#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
Node::Node() //constructor
{
head = NULL;
}
Node::~Node()    //destructor
{
}
void Node::addFirstNode(int n)    //adding the first element in the list
{
node *temp = new node;
temp->data = n;
temp->next = NULL;
head = temp;    
}
void Node :: addLast(int n)    //Adding elements at the end of the list
{
node *last = new node;
last->data = n;
last->next = NULL;
node *temp = new node;
temp = head;        
while (temp->next != NULL) {
temp = temp->next;
}       
temp->next = last;  
}
void Node::display()      //Displaying the list
{
node *temp = head;
while (temp != NULL)
{
cout<<temp->data;
temp = temp->next;
}
}

//the main function:
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
int main()
{
Node a;
a.addFirstNode(101);    //Calling function : addFirstNode
a.addLast(102);         //Calling function : addLast
a.addLast(103);       //Calling function : addLast
a.addLast(104);       //Calling function : addLast
a.display();         //Calling function : display
return 0;
}

Node.h 文件如下所示:

struct node
{
int data;
node *next;
};
class Node
{
private :
node *head;
public:
Node();
~Node();
void addFirstNode(int n);
void addLast(int n);    
void display(); 
};

您应该重命名Node以更好地描述它是什么,例如List.

Node::addFirst()中,将temp->next = NULL;替换为temp->next = head;您不想每次在列表开头添加Node时都扔掉列表。

Node::addLast()中,将node *temp = new node;替换为node *temp = head;您不希望每次在末尾添加Node时都泄漏内存。