【问题标题】:An access violation (segmentation fault) was raised in your program在您的程序中引发了访问冲突(分段错误)
【发布时间】:2016-04-22 11:21:44
【问题描述】:

有多少学生:2(效果很好) 有多少学生:4(它给出错误“在您的程序中引发了访问冲突(分段错误)。”

为什么它会发生在我身上,我已经花了 4 个小时但无法弄清楚。

#include <stdio.h>


struct student 
{
    int rollno;
    char name[20];
};

int main()
{   
    int n,i,j;

    struct student detail[n];

    printf("how many students: ");
    scanf("%d",&n);
    fflush(stdin);

    for(i=0; i<n; i++)
    {            
        printf("enter student no.%d\n",(i));
        printf("Name: ");
        gets(detail[i].name);
        printf("Roll No: ");
        scanf("%d",&detail[i].rollno);
        fflush(stdin);
    }

    for(i=0; i<n; i++)
    {
        printf("Student no. %d Detail\n",(i+1));
        printf("Name:\t\t%s \nRoll No: \t%d\n",detail[i].name,detail[i].rollno);
    }

    getch();
}

【问题讨论】:

  • fflush(stdin); 是 UB
  • 调试器.......................
  • @MartinJames,在这种情况下不需要调试,打开警告就足够了:P

标签: c struct scanf fgets


【解决方案1】:

在您的代码中,主要问题是

 int n,i,j;
 struct student detail[n];

您正在使用未初始化的n。它调用undefined behavior。你需要移动detail[n];的定义你已经扫描了来自用户的值。

也就是说,

  1. 检查scanf()的返回值以确保成功。
  2. gets() 很危险,因为它可能导致缓冲区溢出。请改用fgets()
  3. 按照标准,fflush(stdin) 是 UB,删除它。
  4. getch() 应该是 getchar(),如果只包含 stdio.h

【讨论】:

  • @AlterMann 感谢您的改进,从另一个角度添加信息:)
  • 感谢队友,我将 detail[n] 的定义移到扫描的 'n' 值之后,而不是 fflush 我使用 getchar()。
猜你喜欢
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多