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

C语言链表出现Bus Error问题:输入姓名后程序报错求助

链表Bus Error问题排查与修复

问题根源

  1. 野指针非法访问:char *name,*idNum;未分配有效内存,直接用scanf写入会触发非法内存访问,导致Bus Error。
  2. scanf格式符错误:%[^\n]s是错误写法,正确格式应为%[^\n];且首次scanf前未清理输入缓冲区的换行符,会导致直接读取空内容。
  3. 输出格式混乱: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:25:23