C语言链表出现Bus Error问题:输入姓名后程序报错求助
链表Bus Error问题排查与修复
问题根源
- 野指针非法访问:
char *name,*idNum;未分配有效内存,直接用scanf写入会触发非法内存访问,导致Bus Error。 - scanf格式符错误:
%[^\n]s是错误写法,正确格式应为%[^\n];且首次scanf前未清理输入缓冲区的换行符,会导致直接读取空内容。 - 输出格式混乱:
print_students中的printf未添加换行,所有输出会挤在一起,可读性极差。
修复后的完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Student{ char name[20]; char idNum[10]; int saving; struct Student *next; }Student; Student *head = NULL; void insert_student(){ // 用栈上数组替代野指针,长度匹配结构体定义,避免内存访问问题 char name[20], idNum[10]; int saving; Student *current; Student *new_student = (Student*)malloc(sizeof(Student)); if(new_student==NULL){ printf("==== YOUR MEMORY IS FULL! ====\n"); exit(0); } // 清理输入缓冲区残留的换行符,确保首次输入正常读取 getchar(); printf("Enter your name : "); // 限制读取长度,防止缓冲区溢出(留一位存字符串结束符'\0') scanf("%19[^\n]", name); printf("Enter your Id : "); getchar(); // 清理上一次输入后的换行符 scanf("%9[^\n]", idNum); printf("How many your money : Rp"); scanf("%d", &saving); strcpy(new_student->name, name); strcpy(new_student->idNum, idNum); new_student->saving = saving; new_student->next = NULL; if(head==NULL){ head = new_student; } else{ current = head; while (current->next != NULL) { current = current->next; } current->next = new_student; } } void print_students(){ Student *current; if(head==NULL){ printf("==== THERE IS NO STUDENT YET!\n"); return; // 用return替代exit,避免直接终止程序 } current = head; while (current!= NULL) { printf("Name : %s\n", current->name); printf("id : %s\n", current->idNum); printf("Saving : Rp%d\n\n", current->saving); current = current->next; } } int main(){ insert_student(); print_students(); return 0; }
修改说明
- 用栈上数组
char name[20], idNum[10];替代未初始化的指针,彻底解决野指针问题,同时匹配结构体字段长度防止溢出。 - 每次调用
%[^\n]前用getchar()清理输入缓冲区的换行符,确保用户输入能被正确读取。 - 在
scanf格式符中添加长度限制(如%19[^\n]),避免用户输入过长导致缓冲区溢出。 - 给
print_students的输出添加换行符,提升可读性;将exit(0)改为return,避免程序直接终止。
内容的提问来源于stack exchange,提问作者fyz 08
相关产品推荐
相关产品推荐

