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

C语言实现简单链表出现Segmentation fault错误,求原因分析

链表实现中Segmentation fault错误的原因分析

先看你提供的代码:

#include <stdio.h>
#include <stdlib.h>

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

void printList(struct node *head);

int main() {
    struct node* head;
    head->data =10;
    head->next = NULL;
    printList(head);    
}


void printList(struct node *head){
    struct node *ptr = head;
    if (ptr->next = NULL){
        printf("list is empty");
    }
    while(ptr != NULL){
        printf("%d", ptr->data);
        ptr = ptr->next;
    }
}

触发Segmentation fault的核心原因及其他问题如下:

  • 野指针非法访问(直接触发段错误)
    main函数中声明的head是未初始化的指针,指向内存中随机的未知地址,既没有指向已分配的内存块,也没被初始化为NULL。直接通过head->data和head->next访问并修改该地址内容,属于非法访问系统保护内存区域,必然触发Segmentation fault。

  • 条件判断中的赋值错误
    printList函数里的if (ptr->next = NULL)用了赋值运算符=而非相等判断运算符==,这会强制把ptr->next设为NULL,同时因为赋值表达式结果为NULL(逻辑假),if块内的代码永远不会执行。如果链表原本有后续节点,这个操作还会直接破坏链表结构。

  • 空链表判断逻辑错误
    判断链表为空的正确逻辑是检查头指针本身是否为NULL(即ptr == NULL),而非检查ptr->next == NULL——后者判断的是链表仅有一个节点的情况。如果头指针本身是NULL,直接访问ptr->next又会引发一次野指针访问错误。

修正后的代码示例

#include <stdio.h>
#include <stdlib.h>

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

void printList(struct node *head);

int main() {
    // 为头节点分配内存并检查分配结果
    struct node* head = (struct node*)malloc(sizeof(struct node));
    if (head == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    head->data = 10;
    head->next = NULL;
    printList(head);    
    // 释放内存,避免内存泄漏
    free(head);
}

void printList(struct node *head){
    struct node *ptr = head;
    // 正确判断空链表
    if (ptr == NULL){
        printf("list is empty\n");
        return;
    }
    while(ptr != NULL){
        printf("%d ", ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}

内容的提问来源于stack exchange,提问作者Ayzik Dig

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:05:24