【问题标题】:Exception Handled this was Nullptr?异常处理这是 Nullptr?
【发布时间】:2020-11-24 13:04:14
【问题描述】:

我一直在处理这个任务,并且遇到了这个我几个小时都无法修复的错误。它说抛出未处理的异常,读取访问冲突。我听说你不应该尊重 nullptrs,但我不相信这就是我正在做的事情。

void Linkedlist::insertnode(string key, string value) {
    Node* newNode;                      //This points to the following node
    Node* cursor;                       //This will traverse through list
    newNode = new Node;                 //create a new node
    newNode->data = new HashEntry(key, value);              //Initialize the data 
    newNode->next = nullptr;            //Leave the pointer for the node following after empty at inception;
    if (!head) {
        head = newNode;                 //if head is empty, this will make the first user input the head
        return;
    }
    
    else {
        cursor = head;
        while (cursor->next)
            ;       
        //We'll traverse list to add newNode to tail
        cursor->next = newNode;     //for now the order doesn't matter since they're strings so we add new cluster to tail
    }
}

【问题讨论】:

  • 请发帖minimal reproducible example。您很可能通过 -> 取消引用它。
  • head 在哪里初始化?
  • while (cursor->next); 是一个无限循环。
  • 唯一可以为空的thisLinkedlist 自己的。你是如何创建这个实例的?
  • 请不要发文字图片,发文字。 (它 Linkedlist 实例的 this 为空。您在某处使用了无效的 Linkedlist*。假设问题的原因必然在附近,您可能已经陷入困境你发现它的地方。)

标签: c++ pointers nullpointerexception unhandled-exception nullptr


【解决方案1】:

“读取访问冲突”很可能是一个未初始化的变量。当您尝试从程序内存之外的内存访问数据时,就会发生这种情况。这是您系统的一种保护机制,可防止您覆盖不应覆盖的数据。

因此,我建议检查您对 HashEntry 类的定义以及不在您发布的代码中的指针 head 的定义。

在我看来你的无限循环while (cursor->next);

我明白你想要做什么 - 迭代元素直到你在列表的末尾。但是你必须使用迭代器:

Node* iterator = cursor;
while (iterator)
{
  iterator = iterator->next;
}

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多