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

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

本文关键字:返回 Segmentation 错误 fault 字符 g++ 节点 数据 为什么      更新时间:2023-10-16

我有一个程序,在编译后返回一个错误,然后在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(''), 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字符串有关,我不知道该怎么做来解决这个问题。

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

作为你的代码

node * n = nullptr;

表示将空指针赋给n然后通过

解除对空指针的引用
 n->next = nullptr;

这就导致了分割故障。

使用

解决
node * n = new node();
n->next = nullptr;
n->data = ch;