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

C语言创建单链表打印时出现Segmentation fault(段错误)

单链表段错误问题分析与修复

问题根源

你的代码触发段错误的核心原因是最后一个节点的next指针未初始化:

  • 代码里的newnode->next;是无意义的表达式,没有给新节点的next赋值,导致它是随机的野指针。
  • 当遍历链表到最后一个节点时,temp = temp->next会指向这个野指针,下一次循环判断temp != 0时,野指针大概率不为空,继续访问temp->data就会触发非法内存访问,也就是段错误。

除此之外还有几个小问题:

  • void main()不符合C标准,标准要求main返回类型为int。
  • conio.h是非标准头文件,部分编译器(如GCC)不支持,getch()兼容性差。

修复后的完整代码

// Program to create a singly linked list
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int main()
{
    struct node *head, *newnode, *temp;
    head = NULL; // 用NULL代替0,更符合C语言规范
    int choice = 1;
    
    while (choice)
    {
        if (choice == 1)
        {
            newnode = (struct node *)malloc(sizeof(struct node));
            // 检查内存分配是否成功,避免后续操作出错
            if (newnode == NULL)
            {
                printf("Memory allocation failed!\n");
                return 1;
            }
            
            printf("Enter the data: ");
            scanf("%d", &newnode->data);
            newnode->next = NULL; // 关键:初始化新节点的next为空指针
            
            if (head == NULL)
            {
                head = temp = newnode;
            }
            else
            {
                temp->next = newnode; 
                temp = newnode;
            }
            
            printf("Do you want to continue? Press 1 to continue and 0 to terminate: ");
            scanf("%d", &choice);
        }
        else
        {
            // 输入非1时直接退出循环,避免死循环
            choice = 0;
        }
    }
    
    // 遍历打印链表
    temp = head;
    printf("\nLinked list data: ");
    while (temp != NULL)
    {
        printf("%d\t", temp->data);
        temp = temp->next;
    }
    
    // 若使用GCC编译,可替换getch()为getchar(),或直接注释掉
    // getchar();
    return 0;
}

关键修复点说明

  1. 初始化newnode->next为NULL:确保每个新节点的next都指向合法的空指针,遍历到链表末尾时循环会正常终止,不会访问野指针。
  2. 增加malloc失败检查:内存分配可能失败,此时malloc会返回NULL,提前判断可以避免后续非法操作。
  3. 修正main函数返回类型:改成int main()并添加return 0;,符合C语言标准。
  4. 处理非1的输入:避免用户输入其他数字时陷入死循环。

内容的提问来源于stack exchange,提问作者Bikash kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:06:30