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

字符串数组有序插入首位置触发段错误,求助排查原因

问题分析与修复

段错误根源

你的代码触发段错误的核心原因是**size_t是无符号整数类型**:

  • 在sorted_insert函数的循环中,你用size_t i作为循环变量。当i从0开始减1时,无符号整数不会变为负数,而是溢出成SIZE_MAX(一个极大的正数)。
  • 此时循环条件i >= 0永远为真,代码会继续执行strcmp(dic[i], dyn_w),但i已是非法的超大索引,直接访问了数组外的内存区域,触发段错误。

修复代码

将循环变量i的类型改为有符号整数int即可解决问题,修正后的sorted_insert函数如下:

int sorted_insert(char** dic, char *st_w, int wr_c)
{
    /*check if array has space*/
    if(wr_c >= DIC_SIZE)
    {
        perror("ERROR: array has no free space.");
        exit(-1);
    }
    
    char *dyn_w = malloc(strlen(st_w) + 1); // sizeof(char)固定为1,可省略
    if (!dyn_w) {
        perror("ERROR: failed to allocate memory for word");
        exit(-1);
    }
    strcpy(dyn_w, st_w);

    /*first insert*/
    if (wr_c == 0)
    {
        dic[0] = dyn_w;
        return wr_c + 1;
    }

    /*shift elements to the right until index of insertion is found*/
    int i; // 改用有符号int类型
    for (i = wr_c - 1; ((i >= 0) && (strcmp(dic[i], dyn_w) > 0)); i--)
        dic[i + 1] = dic[i];

    /*insert string*/
    dic[i + 1] = dyn_w;

    return wr_c + 1;
}

额外优化提示

  • 务必检查malloc返回值:内存分配失败时malloc会返回NULL,直接使用会引发后续错误,建议添加上述代码中的空指针判断。
  • 调整fscanf格式串:原代码中"%[^-\n ] "末尾的空格会匹配任意空白字符,可能导致读取行为不符合预期,建议改为"%[^-\n ]"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:25:22