Visual Code arm64环境运行C代码出现segmentation fault如何解决?
段错误问题根源
所有问题都属于内存访问非法/类型不匹配,按触发优先级排序:
- 存储学生信息的数组类型定义错误:
原代码中char n[50]、char c[5]是单字符串数组,仅能存储1个姓名/班级。你尝试用n[i]存储第i个学生的姓名,n[i]本身是单个char类型,将其传给scanf("%s")时,单个char的值会被当做内存地址直接写入,直接触发非法内存访问。 - 输出时格式符与参数类型不匹配:
display函数中用%s输出n2[p]、c1[p],这两个参数都是单个char类型,%s会将其当做字符串首地址去读取内存,直接触发段错误。 - 查询输入的存储变量类型错误:
原代码中n1是单char变量,却用%s接收用户输入的学生姓名,输入的字符串直接覆盖栈上其他内存,触发栈溢出导致段错误。 - 数组越界风险:
存储学号的x数组长度固定为8,如果用户输入的学生数量y>8,写入x[i]时会直接越界覆盖栈内存。 - 未定义行为加剧崩溃概率:
fflush(stdin)是C标准明确的未定义行为,仅Windows平台下部分编译器支持该用法,arm64环境下该操作不仅不会清空输入缓冲区,还可能破坏输入流状态,引发意料之外的内存访问错误。 - 字符串比较逻辑错误:
直接用==比对字符串,实际比对的是两个字符串的首地址而非内容,永远无法得到正确的匹配结果。
修复方案
修改后的可运行代码如下:
#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() { // 定义二维数组存储最多20个学生的信息,姓名最长49字节,班级最长9字节 char n[20][50], c[20][10], query_name[50]; int y, x[20], x1; int p1 = -1; // 初始化为-1标记未找到 printf("Enter the number of students: \n"); scanf("%d", &y); // 限制最大学生数避免数组越界 if(y > 20) { printf("Max supported student count is 20\n"); return 1; } // 跳过scanf残留的换行符,替代fflush(stdin) while(getchar() != '\n'); for (int i = 0; i < y; i++) { printf("Enter the Student Name : \n"); scanf("%49s", n[i]); // 限制输入长度避免溢出 while(getchar() != '\n'); printf("Enter the Student Class : \n"); scanf("%9s", c[i]); while(getchar() != '\n'); printf("Enter the Student Roll No : \n"); scanf("%d", &x[i]); while(getchar() != '\n'); } printf("Enter the Student Name and Roll Number :\n"); scanf("%49s %d", query_name, &x1); for (int i = 0; i < y; i++) { // 用strcmp比较字符串内容 if ((strcmp(n[i], query_name) == 0) && (x[i] == x1)) { p1 = i; break; // 找到直接跳出循环 } } if(p1 == -1) { printf("No Such Entry!!\n"); } else { display(n, x, c, p1); } return 0; }
核心修改点说明
- 将姓名、班级存储数组改为二维数组,适配多学生存储场景
- 替换所有
fflush(stdin)为while(getchar() != '\n')清空输入缓冲区,符合C标准规范 - 字符串比较改为
strcmp函数,查询逻辑优化为匹配到后直接跳出,匹配失败统一输出提示 - 增加输入长度限制和学生数量上限校验,避免缓冲区溢出
- 修正所有格式符与参数类型不匹配的问题
内容的提问来源于stack exchange,提问作者Vaibhav Hawaldar
相关产品推荐
相关产品推荐

