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

构建单链表时触发Segmentation core dumped错误,请求排查代码问题

单链表逆序创建中的段错误排查与修复

核心错误分析

1. 空指针直接访问触发段错误

main函数中node *error = NULL;后直接执行error->num = 1;,空指针未指向任何有效内存区域,对其成员赋值会直接触发Segmentation Fault,这是导致程序崩溃的最直接原因。

2. 链表插入逻辑完全错误

createll函数里的逆序插入逻辑完全写反:

  • 正确的头部插入(实现逆序)应该是让新节点的next指向当前head,再将head更新为新节点;但你的代码写的是new_node = head; head = new_node;,这相当于直接丢弃了malloc分配的新节点(造成内存泄露),head始终保持初始值,根本没构建出链表。

3. 错误处理逻辑无效

即使malloc失败返回error,error本身是无效的空指针,返回后print_list访问它依然会触发崩溃,这个错误处理完全没有意义。

修正后的完整代码

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

typedef struct node{
    int num;
    struct node *next;
}node;

node* createll(node *head);
void print_list(node *head);
void free_list(node *head); // 新增内存释放函数,避免内存泄露

int main(void){
    node *head = NULL;

    head = createll(head);
    print_list(head);
    free_list(head); // 释放链表占用的内存
    return 0;
}

node* createll(node *head){
    int len;
    printf("Size of list: ");
    // 增加输入合法性检查,避免非法输入导致异常
    if(scanf("%d", &len) != 1 || len <= 0){
        printf("Invalid list size\n");
        return NULL;
    }

    for (int i = 0; i < len; i++) {
        node *new_node = malloc(sizeof(node));
        if (new_node == NULL) {
            printf("Memory allocation failed\n");
            // 内存分配失败时,释放已创建的节点,避免内存泄露
            free_list(head);
            return NULL;
        }
        printf("Enter the data: ");
        // 检查输入是否有效
        if(scanf("%d", &new_node->num) != 1){
            printf("Invalid data input\n");
            free(new_node);
            free_list(head);
            return NULL;
        }
        // 正确的头部插入逻辑:新节点指向当前head,更新head为新节点
        new_node->next = head;
        head = new_node;
    }

    return head;
}

void print_list(node *head){
    node *temp = head;
    printf("Data stored is : ");
    while(temp != NULL){
        printf("%d-->", temp->num);
        temp = temp->next;
    }
    printf("\n");
}

void free_list(node *head){
    node *temp;
    while(head != NULL){
        temp = head;
        head = head->next;
        free(temp);
    }
}

修正说明

  • 移除了无效的error指针,改用NULL作为错误返回值,同时在内存分配失败时释放已创建的节点,避免内存泄露
  • 修复了头部插入逻辑,实现了输入数据的逆序链表创建
  • 增加了输入合法性检查,避免非法输入导致的程序异常
  • 新增free_list函数,手动释放链表内存,避免长期运行的内存泄露问题

内容的提问来源于stack exchange,提问作者Syed Istiaq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:52:47