具有链表基本实现的 C++ 中的分段错误(核心已转储)

Segmentation Fault (Core Dumped) in C++ with linked List basic implementation

我知道这里有很多基于在 C++ 中转储的分段错误核心的问题,但我无法解决此错误。我的代码很简单,可以创建一个 link 列表并打印出来。 我想知道为什么它是错误的,因为我是这个主题的新手,想了解更多信息以及它是如何工作的以及错误的含义。

代码如下:


using namespace std;
struct node
{
    int data;
    node *next;
};

node *head =NULL;
void addnode(int x)
{
    node *temp =new node;
    temp->data = x;
    temp ->next = NULL;
    if(head==NULL)
    {
        head = temp;
    }
    else
    {
        node *p =head;
        while(p!=NULL)
        {
            p=p->next;
        }
        p->next =temp;
        temp =NULL;
    }
}

void display(node *head)
{
    node *temp=new node;
    temp = head;
    while(temp!=NULL)
    {
        cout<<temp->data<<" , ";
        temp = temp->next;
    }
    cout<<endl;
}

int main()
{
    cout<<"Hello World";
    node work;
    addnode(12);
    addnode(11);
    addnode(1);
    addnode(22);
    display(head);

    return 0;
}

很可能我弄乱了头指针,这就是为什么会出现这样的错误,但我想知道我的代码在这里做错了什么。

谢谢。非常感谢。

使用

while(p!=NULL)
{
    p=p->next;
}
p->next =temp;

是个问题。当循环中断时,p 是一个 NULL 指针。之后,p->next就不好了。您需要使用:

while (p->next != NULL)
{
    p = p->next;
}
p->next = temp;

对于初学者这个声明

node work;

没有意义。您已经声明了指向头节点的指针。

node *head =NULL;

在此代码段中的函数 addnode

else
{
    node *p =head;
    while(p!=NULL)
    {
        p=p->next;
    }
    p->next =temp;
    temp =NULL;
}

循环

    while(p!=NULL)
    {
        p=p->next;
    }

一直执行到p等于NULL。所以在下一个语句中使用空指针

    p->next =temp;

导致未定义的行为。

此代码段应如下所示

else
{
    node *p = head;
    while( p->next != NULL )
    {
        p = p->next;
    }
    p->next = temp;
}

函数显示有内存泄漏,因为先分配了一块内存,并将其地址分配给指针temp,然后指针重新分配。所以分配的内存不会被删除

node *temp=new node;
temp = head;

函数看起来像

void display(node *head)
{
    for( node *temp = head; temp !=NULL; temp = temp->next )
    {
        cout<<temp->data<<" , ";
    }
    cout<<endl;
}

甚至喜欢

void display( const node *head )
{
    for( const node *temp = head; temp !=NULL; temp = temp->next )
    {
        cout<<temp->data<<" , ";
    }
    cout<<endl;
}

反正列表界面不一致。函数 addnode 处理全局变量 head 而函数 display 获取参数。 使用全局变量是个坏主意,尤其是当函数依赖于这样的变量时。