You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言链表实现报错Segmentation fault (core dumped),求问题解决

排查C语言链表实现中的Segmentation Fault错误

错误原因

你的代码触发段错误的核心问题是**temp指针未初始化就被使用**:

  • 程序仅声明了struct node *temp,但没有给它赋初始值,此时temp是野指针(指向随机内存地址)。
  • 当添加第一个节点时,head被赋值为newNode,但temp仍然是野指针。
  • 当选择继续添加第二个节点时,代码进入else分支,执行temp->next = newNode——这里访问野指针的next成员,直接触发Segmentation Fault。

修复方案

在第一个节点创建完成后,同步把temp指向这个节点,确保后续操作时temp是有效的指针。具体修改是在head = newNode;后面添加一行temp = head;,让temp初始指向链表的第一个节点。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

int main()
{
    struct node *head, *newNode, *temp;
    head = 0;
    int choice=1;
    while(choice)
    {
        newNode = (struct node *)malloc(sizeof(struct node));
        // 新增:检查内存分配是否成功
        if (newNode == NULL) {
            printf("Memory allocation failed!\n");
            return 1;
        }
        printf("Enter Data: \n");
        scanf("%d", &newNode->data);
        newNode->next = 0;
        if (head == 0)
        {
            head = newNode;
            // 新增:让temp初始指向第一个节点
            temp = head;
        }
        else{
            temp->next = newNode;
            temp = newNode;
        }
        printf("Do You Want to Continue(0,1)?\n");
        scanf("%d",&choice);
    }

    temp = head;
    while(temp != 0){
        printf("%d ", temp->data); // 加空格优化输出可读性
        temp = temp->next;
    }
    return 0;
}

额外优化提示

  • 新增malloc空指针检查:避免内存分配失败时后续操作引发未知错误。
  • 输出节点数据时添加空格,让多节点的输出结果更易读。

内容的提问来源于stack exchange,提问作者Sanjay Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:15:36