c++ LinkedList读访问冲突错误
C++ LinkedList read access violation error
我正在尝试用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;
}
相关文章:
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 使用 EvtSetChannelConfigProperty() 函数时出现访问冲突错误
- 引发异常:读取访问冲突.**此**0x40错误
- 在尝试使用CUDA分配内存时,我遇到了访问冲突写入位置错误
- cv::resize() 失败并出现访问冲突错误(由 NULL> 处的 <struct 引起)
- 在 C 代码中调用 Python 函数时第三次出现访问冲突写入位置错误
- 错误 : 异常 : 引发未处理的异常: 读取访问冲突.0xDDDDDDDD临时温度
- 读取访问冲突. _Mycont 在 C++ 中将 udp 数据放入向量时出现 nullptr 错误
- 将 std::string 作为参数从一个 DLL 传递到另一个 DLL 引发访问冲突错误
- 遵循官方 Direct2D 示例,但出现访问冲突错误
- Windows错误:异常:使用从C++到Python的ctypes创建DLL时出现访问冲突或Windows错误193
- C++访问冲突读取位置错误
- Eigen SparseLU解决错误读取访问冲突,这>m_sup_to_col被0x111011101110112
- C++ 抛出读取访问冲突错误,但我不确定为什么。平铺滑块益智游戏
- 为什么我的顶点缓冲区对象出现访问冲突错误?
- 尝试创建结构对象,在位置0x3FE00000中创建访问冲突写入错误
- 销毁 Box2D 主体 - 读取访问冲突错误
- C++数组错误:访问冲突读取位置0xC0000005
- C++LinkedList错误:访问冲突错误
- 错误访问冲突写入位置0x00229C20.尝试在控制台中输入字符串时