链表中写入访问冲突的未知原因

Unknown cause of Write Access Violation in linked list

本文关键字:未知 访问冲突 链表      更新时间:2023-10-16

在最近的一个项目中,目的是通过菜单功能修改链表,我遇到了一个似乎无法修复的错误,因为这行代码非常重要,据我所知,应该按预期工作。我收到的消息是,"异常抛出:写入访问冲突。THIS was nullptr。"我的节点类似乎是错误的来源,错误通过setNext函数体显示。

#include "pch.h"
#include <iostream>
#include <vector>
#include <string>
template<class ItemType>
class Node
{
private:
ItemType value;
Node<ItemType>* next;
public:
Node() {
next = nullptr;
}
Node(const ItemType& val) {
value = val;
next = nullptr;
}
Node(const ItemType& val, Node<ItemType>* nextVal)
{
value = val;
next = nextVal;
}
void setVal(const ItemType& val)
{
value = val;
}
ItemType getVal() const {
return value;
}
void setNext(Node<ItemType>* nextVal)
{
next = nextVal; //Exception thrown here.
}
Node<ItemType>* getNext() const
{
return next;
}
};

同时,在我的linkedlist类中,我缩小了这个异常似乎引起的行,因为代码没有再超出它。谢天谢地,它没有涉及大多数其他类,但这个特定实例的反应似乎就像我调用的节点是一个空指针。

template<class ItemType>
class linkChain {
private:
Node<char>* head;
int count;
//Node<ItemType>* getPointerTo(const ItemType& target) const;
public:
linkChain() {
head = nullptr;
count = 0;
}
linkChain(std::string phrase) : head(nullptr) {
count = phrase.length();
for (int i = count - 1; i >= 0; i--) {
if (head == nullptr) {
head = new Node<char>();
head->setVal(phrase[i]);
}
else {
Node<ItemType>* newNode = new Node<char>(phrase[i]);
newNode->setNext(head);
head = newNode;
}
}
}
void append(const linkChain& chain) {
count += chain.length();
Node<char>* newNode = head;
while (newNode != nullptr) {
newNode = newNode->getNext();
}
Node<char>* nextChain = chain.head;
while (nextChain != nullptr) {
char nextValu = nextChain->getVal();
std::cout << nextValu;
//May be nextVal
Node<char>* tempNode = new Node<char>(nextValu);
//THE LINE BELOW THIS
newNode->setNext(tempNode);
//THE LINE ABOVE THIS
nextChain = nextChain->getNext();
newNode = newNode->getNext();
}
newNode = newNode->getNext();
}
};

这是主函数中用来调用它的代码,其中charVal是一个linkChain。

std::cout << "Please enter a string value to test: ";
std::cin >> testing;
linkChain<char> addThis = linkChain<char>(testing);
std::cout << "Is the string inside: " << charVal->submatch(addThis) << "n";

我不是最擅长节点的,所以如果有任何关于如何修复我一无所知的错误的建议,我将不胜感激。其他在线答案对这个问题给出了模糊或无关的答案,所以他们对我几乎没有帮助。

以下while循环是一个确定的问题(如果没有完整的MCVE,如注释中所要求的,我无法正确检查其他错误(:

while (newNode != nullptr) {
newNode = newNode->getNext();
}

当该循环结束时,则newNodenullptr!但是,在下一个循环中,几行之后,您将取消引用nullptr值:

while (nextChain != nullptr) {
//...
//THE LINE BELOW THIS
newNode->setNext(tempNode);
//THE LINE ABOVE THIS
//...

在第一个while循环中,您应该做的是检查next指针:

while (newNode>getNext() != nullptr) {
newNode = newNode->getNext();
}

当您指向列表中的最后一个节点时,此循环将退出。