将节点附加到链接列表时的Segfault

时间:2015-03-24 21:37:21

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

我一直在尝试使用C ++重写一些基本的数据结构,以便在OOP的一些基础知识上刷新内存,但我已经遇到了一个愚蠢的问题。

我正在尝试构建一个单链表,将字符串“Hello”和“World”附加到列表中,然后查看列表中的所有内容。这是一项非常简单的任务,但是当我运行以下代码时,我遇到了分段错误:

  

driver.cc

#include <iostream>
#include <string>
#include "SinglyLinkedList.h"

int main() 
{
    SLL<std::string> List;
    List.Append("Hello");
    List.Append("World");

    List.visitAll(std::cout);

    return 0;
}
  

Node.h

#ifndef NODE_H
#define NODE_H

template <class T>
class Node {
    public:
        Node<T>() {} 
        Node<T>(T init) { data = init; next = nullptr; }

        void setData(T newData) { data = newData; }
        void setNext(Node<T> *nextNode) { next = nextNode; }

        const T getData() { return data; }
        Node<T> *getNext() { return next; }
    private:
        T data;
        Node<T> *next;
};

#endif
  

SinglyLinkedList.h

#ifndef SINGLY_LINKEDLIST_H
#define SINGLY_LINKEDLIST_H

#include "Node.h"
#include <iostream>

template <class T>
class SLL {
    public:
        SLL<T>() { head = nullptr; size = 0; }
        ~SLL<T>() {}
        void Append(T added);
        void Delete(T deleted);
        void visitAll(std::ostream &outs);
    private:
        Node<T> *head;
        long size;
};

template <class T>
void SLL<T>::Append(T added) 
{
    Node<T> *newNode = new Node<T>(added);

    Node<T> *temp = head;

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

        temp->setNext(newNode); // seg fault here
    } 
    else {
        head = newNode;
    }
}

template <class T>
void SLL<T>::visitAll(std::ostream &outs)
{
    Node<T> *temp = head;

    while(temp)
    {
        outs << temp->getData() << std::endl;
        temp=temp->getNext();
    }
}

#endif

只需手动调试,我创建了一个data = "Hello"next = nullptr的新节点。由else方法中的void SLL<T>::Append追加temp == nullptr。但是,在第二个Append上,while循环运行一次,然后在调用Node类的setter时崩溃。我无法弄清楚为什么会这样。

我期待看到

Hello
World

我是否过于具有隧道视野?这很傻。对不起,如果它太基础了......

谢谢, erip

2 个答案:

答案 0 :(得分:3)

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

temp->setNext(newNode); // seg fault here

那是因为你在while时突然离开temp == nullptr圈。

使用:

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

temp->setNext(newNode);

答案 1 :(得分:1)

Append中的while循环以temp为空指针结束,因此没有temp->setNext()

相关问题