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

求解:我的CodeChef竞赛代码为何出现segmentation fault(core dumped)错误?

问题分析与解决:Segmentation Fault (Core Dumped) 错误

错误核心原因

你的代码触发段错误的直接原因是在读取n的值之前就定义了变长数组a[n]和b[n]。C语言中,变长数组的大小必须是确定的整数值,但此时n未被初始化,是随机垃圾值:

  • 若垃圾值过大,会直接导致栈空间溢出;
  • 若垃圾值较小,后续读取的n与数组实际大小不匹配,会引发数组越界访问,同样触发段错误。

修正后的代码

#include <stdio.h>

int main(void) {
    int t;
    scanf("%d", &t);
    while(t--)
    {
       int n;
       int max = 0;
       int count = 0;
       // 先读取n的值,再定义数组
       scanf("%d", &n);
       int a[n];
       int b[n];
       for(int j = 0; j < n; j++)
       {
           scanf("%d", &a[j]);
       }
       for(int k = 0; k < n; k++)
       {
           scanf("%d", &b[k]);
       }
       for(int x = 0; x < n; x++)
        {
           // 修正逻辑:明确判断a[x]和b[x]都不为0,避免原表达式的逻辑歧义
           if(a[x] != 0 && b[x] != 0)
           {
               count++;
           }
           else
           {
               if(count > max)
               {
                   max = count;
               }
               count = 0; // 无论是否更新max,都要重置计数
           }
       }
       if(count > max)
           max = count;
       printf("%d\n", max); // 增加换行符,保证多组测试用例输出格式正确
    }
    return 0;
}

额外优化说明

  1. 逻辑修正:原表达式a[x]&&b[x]!=0存在逻辑歧义,它等价于(a[x]) && (b[x]!=0),如果你的需求是判断a[x]和b[x]都不为0,应写成a[x] != 0 && b[x] != 0。
  2. 输出格式:添加换行符\n,避免多组测试用例的结果连在一起,防止判题系统误判。
  3. 内存选择:若题目中n的取值范围较大(比如1e5级别),建议使用malloc/free动态分配内存,避免栈空间不足的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:00:59