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

arm64架构Visual Studio Code运行C代码出现zsh: segmentation fault问题

段错误原因排查
  • 直接触发原因:输入学生姓名时发生内存越界。代码中n[i][j]是单个char类型的字符变量,而scanf("%s", n[i][j])尝试将整个输入的字符串写入单个字符的内存空间,瞬间超出合法内存范围,直接触发段错误,这就是输入姓名后立即崩溃的原因。
  • 变长数组非法:全局变量m、n未初始化默认值为0,display函数的参数char n2[m][n]定义了长度为0的非法变长数组,调用时必然出现内存访问异常。
  • 班级存储逻辑错误:存储班级的c是长度为5的一维char数组,scanf("%s", c[i])同样是向单个字符地址写入字符串,也会触发内存越界。
  • 输出逻辑错误:display函数中使用%s格式符输出n2[p][j](单个字符值),会把字符值当作内存地址访问,只要执行到这里必然触发段错误。
  • 数组容量不足:学号数组x长度仅为8,当输入学生数量超过8时会出现数组越界。
  • 匹配逻辑漏洞:变量a初始值为0,未找到匹配学生时依然会调用display函数输出错误数据。
修复方案

核心修改点

  1. 移除无用的全局变量m、n,修改display函数参数为固定维度的二维数组,适配主函数中定义的数组长度
  2. 删除输入姓名时的内层循环,直接向n[i](字符串首地址)写入完整姓名
  3. 将班级存储数组c修改为二维数组,每个元素对应一个学生的班级字符串
  4. 修正display函数的输出逻辑,直接用%s输出完整字符串,不需要遍历单个字符
  5. 扩容学号数组x到50,匹配最大50个学生的数量限制
  6. 修正匹配逻辑,a初始值设为1,找到匹配学生后再设为0,使用标准库strcmp做字符串匹配,避免手写逻辑出错

修复后完整代码

#include <stdio.h>
#include <string.h>

void display(char n2[][50], int x2[], char c1[][10], int p);

void display(char n2[][50], int x2[], char c1[][10], int p)
{
  printf("Student Name :  %s \n", n2[p]);
  printf("Student Roll No : %d \n", x2[p]);
  printf("Student Class : %s \n", c1[p]);
}


int main()
{
  char n[50][50], c[50][10], n1[50];
  int y, x[50], x1;
  int p1 = 0;
  int a = 1;

  printf("Enter the number of students: \n");
  scanf("%d", &y);
  if(y > 50) {
    printf("Max student number is 50");
    return 1;
  }

  for (int i = 0; i < y; i++)
  {
    printf("Enter the %d Student Name : \n", i + 1);
    scanf("%s", n[i]);

    printf("Enter the Student Class : \n");
    scanf("%s", c[i]);
    printf("Enter the Student Roll No : \n");
    scanf("%d", &x[i]);
  }

  printf("Enter the Student Name and Roll Number :\n");
  scanf("%s %d", n1, &x1);

  for (int i = 0; i < y; i++)
  {
    if (x[i] == x1 && strcmp(n[i], n1) == 0)
    {    
      p1 = i;
      a = 0;
      break;
    }
  }

  if (a == 0)
  {
    display(n, x, c, p1);
  }
  else
  {
    printf("No Such Entry!!");
  }

  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:39:03