【问题标题】:error : exception : Unhandled exception thrown: read access violation. temp was 0xDDDDDDDD错误:异常:抛出未处理的异常:读取访问冲突。温度为 0xDDDDDDDD
【发布时间】:2018-11-16 21:44: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 *temp = new node; 存在内存泄漏,您分配了一个对象,然后立即通过执行temp = head 来倾斜它。同时显示调用它的代码,以便我们确切地知道你在做什么
  • Node::addFirst()temp-&gt;next = NULL; 应该是temp-&gt;next = head;
  • 但是我希望head等于temp,因此我首先设置了temp节点的数据和next,然后将head等同于temp节点。这不应该工作吗?
  • node.h 长什么样子?

标签: c++ linked-list


【解决方案1】:

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

Node::addFirst() 中,将temp-&gt;next = NULL; 替换为temp-&gt;next = head; 您不希望每次在列表开头添加Node 时都将其丢弃。

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

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2017-01-27
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多