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

C程序运行报zsh abort错误,循环输入提前终止请求排查

问题排查:scanf循环触发"zsh abort"错误的原因及修复

核心错误分析

  • 数组越界访问:代码中scanf(" %c", &right_choices[20]);始终写入数组right_choices的第21个元素——C语言数组索引从0开始,char right_choices[20]的合法索引范围是0到19,right_choices[20]属于非法内存地址。重复写入该地址会触发内存访问错误,直接导致"zsh abort"。
  • 循环次数不符预期:for( k=1; k < 20; k++)的执行逻辑是k从1到19,仅运行19次,和你预期的20次循环不匹配。

修复后的代码

#include<math.h>
#include<stdio.h>
#include"hw1.h"

int main (int argc, char *argv[]) {
    int num_choices, k; 
    char right_choices[20];
    
    do {
        printf("Enter number of choices:\n");
        scanf("%d", &num_choices);
    }
    while ((num_choices > 26) || (num_choices < 1));

    num_choices = num_choices - 1 + 'A';
    printf("Max choice:%c\n", (char)num_choices);

    printf("Enter answer key:\n");
    // 修正循环索引,从0开始到19,执行20次,写入数组合法位置
    for(k = 0; k < 20; k++)
        scanf(" %c", &right_choices[k]);

    return 0;
}

额外说明

数组越界属于C语言的未定义行为,不同系统上的表现可能不一致(你提到Linux下能运行只是偶然情况,未定义行为的结果完全不可预测)。修正后循环从索引0开始,配合k < 20的条件,确保刚好执行20次,且每次写入数组的合法内存区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:16:24