当我将节点指向数据字符时,为什么 g++ 返回 'Segmentation fault' 错误?

Why is g++ returning a 'Segmentation fault' error when I point a node to a char of data?

我有一个程序在编译后 returns 出错,然后 运行 在 g++ 中出错。我知道是因为当我在 Visual Studio 中测试此代码时,当我尝试将新节点数据指针设置为等于某个值时会发生此错误。更具体地说,当我尝试在该行代码处设置 n->data = ch; Visual Studio 中断(停止)时。对于上下文,这是我的头文件的一部分(n->data = ch; 接近尾声):

#include <ostream>

class LinkedList
{
public:
        LinkedList();
        ~LinkedList();

        void add(char ch);
private:
    struct node
    {
            node();
            char data;
            node * next;
    };
    node * head;
    node * curr;
    node * prev;
};
LinkedList::LinkedList() : head(nullptr), curr(nullptr), prev(nullptr);
LinkedList::node::node() : data('[=11=]'), next(nullptr);
LinkedList::~LinkedList()
{
    if (!head) // head is null and so list is empty
    {
            return; //nothing to delete
    }

    for(curr = head; head; /* head isn't NULL*/ delete curr /*delete first element*/)
    {
            curr = head;  // set curr to head of list
            head = curr->next;  // move head over to next element (or make it null)
    }
}
void LinkedList::add(char ch)
{
    node * n = nullptr;
    n->next = nullptr; //my compiler doesn't like this
    n->data = ch; // or this
    //irrelevant code after this.
}

我希望我能给你们更多的背景信息,但我不知道为什么这不起作用。即使它 与 C 字符串有关,我也不知道如何解决这个问题。

作为您的代码

node * n = nullptr;

说将空指针分配给 n 然后你通过

取消引用该空指针
 n->next = nullptr;

因此,它会导致分段错误。

解决使用

node * n = new node();
n->next = nullptr;
n->data = ch;
void LinkedList::add(char ch)
{
    node * n = nullptr; // ##
    n->next = nullptr; //my compiler doesn't like this
    n->data = ch; // or this

    ...

第一行(标记为##)定义了一个指向node的指针,并初始化为nullptr,所以指针实际指向"nothing".

因此,您不能使用该指针为 node 数据结构字段(n->nextn->data)设置值,因为它没有指向任何内容行。

解决这个问题的方法是创建一个新的 node 实例(例如使用 new),然后准备该实例的字段,使用 n->nextn->data.