程序停止工作,运行时会显示错误消息

时间:2017-10-03 14:42:45

标签: c segmentation-fault

每个软件都会显示此错误消息。

  

它已停止工作检查在线解决方案并关闭程序

代码中没有错误,但是当我运行这个程序时,我收到了这个错误,我发现大多数需要用户输入的程序都停止工作。我使用过代码块,C free,dev C ++

#include<stdio.h>
#include<conio.h>
struct student
{
    int roll;
    char name[10];
} stu1 = {100, "ram"};

main()
{
    struct student stu2;
    printf("2nd student name is:  %s \n",stu1.name);
    printf("second student roll no:  %s \n ",stu1.roll);
    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",&stu2.name);
    printf("2nd student name is:  %s \n",stu2.name);
    printf("second student roll no:  %s \n ",stu2.roll);

    getch();
}

包含错误消息的图片:https://i.stack.imgur.com/ZZsAU.png

2 个答案:

答案 0 :(得分:0)

#include<stdio.h>

struct student
{
    int roll;
    char name[10];
}stu1 = {100, "ram"};



int main()
{
    struct student stu2;
    printf("2nd student name is:  %s \n",stu1.name);
    printf("second student roll no:  %d \n ",stu1.roll); // line 1
    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",stu2.name); // line 2
    printf("2nd student name is:  %s \n",stu2.name);
    printf("second student roll no:  %d \n ",stu2.roll); // line 3

    return 0;
}

我已经纠正了这样的代码。第一,第二和第三行是我认为的问题。如上所示更改这些行代码不再运行到分段错误。

注意:不要使用scanf进行用户输入。如果您完全使用scanf,请始终检查其返回值。 scanf %s是一个错误:它无法阻止更长时间输入的缓冲区溢出。

答案 1 :(得分:0)

这可能是另一种方法:

#include<stdio.h>
#include<conio.h>

typedef struct
{
    int roll;
    char *name;
} studentT;

int main()
{
    studentT stu1, stu2;

    stu1.roll = 100;
    stu1.name = "ram";

    printf("2nd student name is:  %s \n",stu1.name);
    printf("second student roll no:  %d \n ",stu1.roll);

    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",&stu2.name);

    printf("2nd student name is:  %s \n",stu2.name);
    printf("second student roll no:  %d \n ",stu2.roll);

    getch();
}