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

C语言链表实现出现Segmentation Fault,求问题排查与解决

解决链表append函数导致的Segmentation Fault问题

我一眼就瞅出问题出在你的append函数的遍历逻辑上了——这绝对是链表新手最容易踩的经典坑!

先看你这段出问题的代码:

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

当这个循环结束时,cursor已经变成NULL了(因为你一直让它指向next,直到它本身为空)。这时候你去访问cursor->next,本质就是在操作一个空指针的成员,系统直接给你抛出Segmentation Fault完全合理。

正确的做法应该是遍历到链表的最后一个有效节点,也就是当cursor->next == NULL的时候就停下来,这时候的cursor就是你要找的尾节点,直接把新节点挂到它的next上就行。

修正后的append函数应该是这样的:

node* append(int value,node *head){
    // 创建新节点
    node* new_node = create(value,NULL);
    // 空链表的情况直接返回新节点作为头
    if (head == NULL) {
        head = new_node;
        return head;
    }
    else{
        node* cursor = head ;
        // 遍历到尾节点(当cursor的next为空时停止)
        while (cursor->next != NULL) {
            cursor = cursor->next ;
        }
        // 把新节点挂到尾节点后面
        cursor->next = new_node;
        return head;
    }
}

另外给你提两个小建议(虽然不影响功能,但能让程序更友好/健壮):

  • 主程序里输入节点时,你用n来提示节点序号,比如输入长度3的话,会先提示"enter the value of the 2 node",然后是1、0,用户看着会有点懵。可以改成printf("enter the value of the %d node\n", (初始长度 - n));,这样序号就从1开始递增了。
  • 程序结束前记得释放链表的内存,不然会造成内存泄漏。可以加一个释放函数:
void free_list(node *head) {
    node *temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
}

然后在main函数的return 0;之前调用free_list(head);就行。

内容的提问来源于stack exchange,提问作者iLyes H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:08:09