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

结构体指针与内部指针:无数组实现学生信息程序崩溃求助

问题排查与解决方案

核心崩溃原因

程序崩溃的直接原因是录入年龄时的scanf调用错误:

scanf("%d", (ptr+i)->age);

scanf的%d格式符要求传入一个int*类型的指针(即变量的地址),但这里直接传入了(ptr+i)->age的数值(int类型),导致scanf试图向无效地址写入数据,触发内存访问违规错误(0xC0000005)。

其他潜在问题

  1. 缺少stdlib.h头文件:代码中使用malloc但未包含其声明所在的<stdlib.h>,编译器会默认malloc返回int类型,在64位系统中会导致指针截断,引发未定义行为。
  2. 内存泄漏:所有通过malloc分配的内存未被释放,长期运行会耗尽系统资源。
  3. 错误处理不完整:内存分配失败时未清理已分配的内存,会造成泄漏。

修正后的完整代码

#include<stdio.h>
#include<string.h>
#include<stdlib.h>  // 新增:包含malloc和free的声明

typedef struct
{
    char *name;
    char *std_id;
    int age;
} students;

int main()
{
    int num;
    printf("Number of students: ");  // 调整提示语匹配题目示例
    scanf("%d", &num);

    students* ptr = malloc(num * sizeof(*ptr));
    if(ptr == NULL)
    {
        printf("memory allocation failed!\n");
        return 1;  // 用非0返回码表示错误
    }

    for(int i=0; i<num; i++)
    {
        printf("\nName of the student%d: ", i+1);
        (ptr+i)->name = malloc(sizeof(char)*20);
        if((ptr+i)->name == NULL)
        {
            printf("memory allocation failed!\n");
            // 提前释放已分配的内存
            for(int j=0; j<i; j++)
            {
                free((ptr+j)->name);
                free((ptr+j)->std_id);
            }
            free(ptr);
            return 1;
        }
        scanf("%s", (ptr+i)->name);

        printf("std_id of the student%d: ", i+1);
        (ptr+i)->std_id = malloc(sizeof(char)*10);
        if((ptr+i)->std_id == NULL)
        {
            printf("memory allocation failed!\n");
            free((ptr+i)->name);
            for(int j=0; j<i; j++)
            {
                free((ptr+j)->name);
                free((ptr+j)->std_id);
            }
            free(ptr);
            return 1;
        }
        scanf("%s", (ptr+i)->std_id);

        printf("age of the student%d: ", i+1);
        scanf("%d", &((ptr+i)->age));  // 修复:传入age的地址
    }

    // 输出学生信息,匹配题目示例格式
    for(int i=0; i<num; i++)
    {
        printf("\nName of the student%d is: %s", i+1, (ptr+i)->name);
        printf("\nstd_id of the student%d is: %s", i+1, (ptr+i)->std_id);
        printf("\nage of the student%d is: %d", i+1, (ptr+i)->age);
        printf("\n");
    }

    // 释放所有分配的内存
    for(int i=0; i<num; i++)
    {
        free((ptr+i)->name);
        free((ptr+i)->std_id);
    }
    free(ptr);

    return 0;
}

关键修正点说明

  • 修复scanf年龄输入:将(ptr+i)->age改为&((ptr+i)->age),确保scanf能正确写入年龄值。
  • 添加stdlib.h:解决malloc函数声明缺失的问题。
  • 内存泄漏修复:程序结束前依次释放每个学生的name、std_id,最后释放学生数组指针。
  • 增强错误处理:内存分配失败时,提前清理已分配的内存,避免泄漏。
  • 格式匹配:调整提示语和输出格式,与题目给出的示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:05:19