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

C语言编写RandList生成随机值单向链表出现段错误问题求解

段错误核心原因

你的代码存在3个关键问题,其中野指针非法访问是触发段错误的直接原因:

  • 野指针未初始化就访问:你定义struct el* head;之后没有将其初始化为NULL,也没有分配对应内存,直接执行head -> data = -150;写入了随机无效内存地址,属于典型的非法内存访问,触发段错误。你删掉后续代码仍能运行属于未定义行为的随机表现,不代表代码逻辑正确。
  • 空链表判断逻辑错误:你使用head->data == -150判断是否为第一个节点的逻辑完全不成立,判断空链表直接判断head == NULL即可,不需要额外的占位值。
  • 随机数种子初始化位置错误:srand((unsigned)time(NULL))放在RandList函数中会导致短时间内多次调用函数时生成完全相同的随机数序列,正确做法是整个程序仅在main函数开头执行一次srand初始化。
修正后的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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

struct el* RandList(int n){
    int i;
    struct el* head = NULL;
    struct el* tail = NULL; // 用尾指针避免每次遍历链表,提升性能
    for (i=0;i<n;i++){
        struct el* temp = malloc(sizeof(struct el));
        // 增加malloc失败判断,避免空指针访问
        if (temp == NULL) {
            perror("malloc failed");
            exit(EXIT_FAILURE);
        }
        temp -> data = (rand() % 201) - 50; // 模201才能覆盖0-200,减50后是-50到150
        temp -> next = NULL;
        if (head == NULL){
            head = temp;
            tail = temp;
        } else {
            tail->next = temp;
            tail = temp;
        }
    }
    return head;
}

int main(){
    srand((unsigned) time(NULL)); // 整个程序仅初始化一次随机种子
    struct el* head = RandList(4);
    // 遍历输出验证
    struct el* p = head;
    while(p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    // 补充内存释放逻辑,避免内存泄漏
    p = head;
    while(p != NULL) {
        struct el* temp = p;
        p = p->next;
        free(temp);
    }
    return 0;
}
额外优化说明
  • 新增了tail尾指针,不需要每次插入节点都遍历整个链表,时间复杂度从O(n²)降低到O(n)
  • 修正了随机数生成逻辑:rand()%200只能生成0-199的数,减50后是-50到149,缺少150这个值,改为rand()%201才能覆盖完整的取值范围
  • 增加了malloc失败的异常处理,避免内存申请失败时的空指针访问
  • 补充了链表内存释放逻辑,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:24:02