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

使用fscanf读取文件整数到数组时触发Segmentation fault问题排查

段错误原因及修复方案

核心问题:循环失控导致数组越界

你的代码里while (fscanf(file, "%d", &num_in))这个循环条件存在致命问题:
fscanf的返回值是成功读取的变量个数,当文件读到末尾时会返回EOF,遇到格式不匹配时返回0,但你的循环只判断返回值是否非零——这意味着即使读取失败(比如到了文件尾),循环也不会停止。i会一直递增,超过numbers数组10000个元素的上限,访问不属于数组的内存,直接触发段错误。

修复步骤

  1. 修正循环终止条件:同时判断fscanf成功读取一个整数(返回值为1),以及i未超出数组容量,双重防止越界:
    while (i < 10000 && fscanf(file, "%d", &num_in) == 1) 
    {
        numbers[i] = num_in;
        i++;
    }
    
  2. 清理字符串格式:perror的参数不需要手动加换行,它会自动追加;printf里的换行用\n规范写法:
    perror("Error opening and reading file");
    // ...
    printf("%d\n", numbers[j]);
    
  3. 关闭文件避免资源泄漏:文件操作完成后必须调用fclose释放资源。
  4. 优化输出逻辑:输出时用实际读取到的元素数量i作为上限,避免输出未初始化的数组元素。

完整修复代码

int main(void) {
    FILE *file;
    int num_in;
    int numbers[10000];

    file = fopen("/Users/foo/aa/extra/sort/rand10k", "r");

    if (file == NULL) 
    {
        perror("Error opening and reading file");
        return 1;
    }

    int i = 0;

    while (i < 10000 && fscanf(file, "%d", &num_in) == 1) 
    {
        numbers[i] = num_in;
        i++;
    }

    for (int j = 0; j < i; j++) 
    {
        printf("%d\n", numbers[j]);
    }

    fclose(file);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:35:26