c++ LinkedList读访问冲突错误

C++ LinkedList read access violation error

本文关键字:错误 访问冲突 LinkedList c++      更新时间:2023-10-16

我正在尝试用c++编写我自己的LinkedList应用程序。现在我被困在一个点,我需要一些帮助。我的应用程序触发访问违反错误,我不知道为什么。我很感激任何帮助。当我删除列表-> remove(0)之后的方法"printList()"(现在这个方法在列表中只有1个节点),它的工作,但我想看到输出。如果我再次插入printList()方法,它会再次崩溃。

下面是我的代码:

LinkedList.cpp

#include "LinkedList.h"
#include <iostream>
LinkedList::LinkedList() {
    head = NULL;
    tail = NULL;
}
LinkedList::~LinkedList() {
    std::cout << "Die Liste wurde aus dem Speicher gelöscht.";
}
int LinkedList::append(const char* text) {
    //new Node
    Node* node = new Node();
    node->setData(text);
    node->setNext(NULL);
    //temp pointer
    Node* tmp = head;
    if (tmp == NULL) {
        //List empty && set first node to head
        head = node;
    } else {
        //list not empty, find the end of the list
        while (tmp->getNext() != NULL) {
            tmp = tmp->getNext();
        }
        tmp->setNext(node);
    }
    return 0;
}
int LinkedList::remove(int p) {
    int counter = 0;
    //temp pointer
    Node* node = head;
    delete node;
    return 0;
}
void LinkedList::printList() {
    Node* node = head;
    if (node == NULL) {
        std::cout << "Empty";
    } else if (node->getNext() == NULL) {
        //only one node in the list
        std::cout << node->getData() << " --> NULL" << std::endl;
    } else {
        do {
            std::cout << node->getData() << " --> ";
            node = node->getNext();
        } while (node != NULL);
        std::cout << "NULL" << std::endl;
    }
}

node.cpp

#include "node.h"
#include <iostream>
Node::Node() {
    //NOTHING
}
Node::~Node() {
    std::cout << "Node aus Speicher gelöscht.";
}
void Node::setData(const char* d) {
    data = d;
}
void Node::setNext(Node* n) {
    next = n;
}
const char* Node::getData() {
    return data;
}
Node* Node::getNext() {
    return next;
}

main.cpp

#include "LinkedList.h"
int main() {
    LinkedList* liste = new LinkedList();
    liste->printList();
    liste->append("10");
    liste->printList();
    liste->remove(0);
    liste->printList();
    return 0;
}

在'有限范围' remove函数中,您删除头节点(通过node变量)。这意味着下次您尝试打印列表时,您将尝试使用已删除的值,因此将调用未定义行为。

在实现remove函数之前,一般情况下应该将头指针设置为null。

int LinkedList::remove(int p) {
    if(head){
        delete head;
        head = nullptr;
    }
    return 0;
}