【问题标题】:How to resolve segmentation fault singly linked list?如何解决分段错误单链表?
【发布时间】:2021-11-02 02:57:21
【问题描述】:

编辑:刚刚尝试做while (temp != NULL && newNode->info > temp->info){,但由于某种原因仍然无法正常工作,我尝试输入 5 和 4 并再次出现分段错误

对不起,我对这个有点陌生,我正在尝试制作一个排序的单链表。我不确定它有什么问题,如果有人可以帮助我解决这个问题,我将不胜感激?

我可能输入了几个值,但由于某种原因每次输入不同数量的值(不是因为我输入了 -1)。然后它只是说“发生异常。分段错误。”在这个特定的行上,我不知道为什么,因为我小心地比较值而不是内存地址:

while (newNode->info > temp->info){

完整代码:

#include <iostream>
using namespace std;

class node {
public:
    int info;
    node *next;

    node (int data, node *ptr = 0) {
        info = data;
        next = ptr;
    }
};

class osll{

    public:
    node *head, *tail;

    osll(){
        head = tail = 0;
    }

    bool isEmpty(){
        return head == 0;
    }

    void sort(int input){

        node *newNode = new node (input);

        if (isEmpty()){
            newNode ->next = head;
            head = newNode;
            if (tail == 0)
                tail = head;
        }
        if (newNode ->info > head ->info){

            node *temp = head;
            while (newNode->info > temp->info){
                temp = temp ->next;
            }
            
            // will figure out how to link newNode to 
            // whatever temp value that stops here
            // once this error goes away
        }
    }

    
};



int main () {
    osll l;
    int input = 0;

    while (input != -1) {
        cout << "Enter a value: ";
        cin >> input;
        l.sort(input);
    }

    return 0;

}

【问题讨论】:

  • 如果temp 变成空指针,你的while循环会发生什么?
  • 您输入的是什么值?我刚刚输入了大量的随机数,从未引起过段错误。
  • 您是否尝试先搜索互联网?我相信我在上周看到了相同的问题标题。
  • 在while循环中检查temp != NULL
  • 看来,如果我继续以递减的方式添加值,它仍然有效,但直到增加它似乎不起作用,所以 5 4 3 2 1 有效,但 5 4 3 88 返回了分段故障信息

标签: c++ pointers segmentation-fault nodes singly-linked-list


【解决方案1】:

如果您的新数字是列表中最大的数字,则会导致分段错误,因为您没有在 while 循环中检查是否到达列表末尾。在最后一个元素 temp 之后将为空,因此 .temp-&gt;info 将导致分段错误。

所以你应该做例如(第 40 行)

while (temp != null && newNode->info > temp->info)

【讨论】:

  • 刚试过输入3和5还是不行,不知道为什么
  • 我只修复了段错误。我没有完成代码,所以它没有链接,但你不再得到一个段错误。如果这样做,请确保在运行之前保存并重新编译代码(容易忘记)。
  • @minhanhb 永远不要假设您只有一个错误。如果newNode -&gt;info &gt; head -&gt;info 不正确,代码似乎也会丢弃节点。
  • 它一直在丢弃。它无处链接。但万一 3 5 newNode -&gt;info &gt; head -&gt;info 为真
猜你喜欢
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多