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

运行Round Robin算法时读取文件触发Segmentation Fault问题求助

轮转调度算法读取文件触发Segmentation Fault问题排查与修复

问题根源分析

从你提供的代码和场景来看,触发段错误的核心原因集中在以下几点:

  • 文件打开未做有效性校验:fopen可能因文件不存在、权限不足返回NULL,后续直接用无效的filehandle调用fgets会直接引发崩溃。
  • numprocess赋值逻辑错误:代码里numprocess = printf("%s",lyne);完全是逻辑失误——printf返回的是输出字符数,这会导致numprocess被错误赋值,后续若依赖该变量判断数组边界,必然触发越界访问。
  • strtok返回值未校验:如果文件行格式不符合预期(比如缺少字段、分隔符错误),strtok会返回NULL,此时调用atoi(NULL)会引发未定义行为,甚至直接崩溃。
  • 数组越界未限制:reccount持续递增,若超过进程数组p的预设容量,写入p[reccount]会越界访问内存,触发段错误。

修复后的代码示例

else if (select == 2)
{
    FILE *filehandle;
    char lyne[100];
    char *item;
    int reccount = 0;
    // 打开文件并校验是否成功
    filehandle = fopen("Input_Data1.txt", "r");
    if (filehandle == NULL)
    {
        perror("Failed to open file");
        return; // 或根据程序逻辑做其他错误处理
    }

    // 先统计文件中的进程数(假设每行对应一个进程)
    numprocess = 0;
    while (fgets(lyne, 99, filehandle))
    {
        numprocess++;
    }
    rewind(filehandle); // 将文件指针重置到开头

    // 重新读取并解析进程数据
    reccount = 0;
    while (fgets(lyne, 99, filehandle) && reccount < numprocess)
    {
        printf("%s", lyne);
        item = strtok(lyne, " ");
        if (item == NULL)
        {
            fprintf(stderr, "Invalid line: missing arrival time\n");
            continue;
        }
        p[reccount].arrivetime = atoi(item);

        item = strtok(NULL, " ");
        if (item == NULL)
        {
            fprintf(stderr, "Invalid line: missing burst time\n");
            continue;
        }
        p[reccount].bursttime = atoi(item);

        reccount++;
    }
    // 关闭文件
    fclose(filehandle);
}

额外注意事项

  1. 若p是静态数组,务必确保其大小不小于实际进程数;如果进程数不确定,建议用malloc/realloc动态分配内存,从根源避免越界。
  2. 保证输入文件每行严格遵循[到达时间] [执行时间]的格式,必要时可增加更严格的格式校验逻辑。
  3. 完善错误处理流程,比如文件打开失败、格式错误时给出明确提示,便于快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:01:11