简体   繁体   English

程序停止工作并在我运行时显示错误消息

[英]Program stops working and an error message is displayed when i run it

This error message is shown in every software.每个软件中都会显示此错误消息。

it has stop working check online solution and close the program它已停止工作检查在线解决方案并关闭程序

There is no error in code but when I run this program I got this error and I found that most of the program where user input is required it stops working.代码中没有错误,但是当我运行这个程序时,我收到了这个错误,我发现大多数需要用户输入的程序都停止工作了。 I have used code blocks, C free, dev C++我使用过代码块、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();
}

Image with error message: https://i.stack.imgur.com/ZZsAU.png带有错误消息的图像: https : //i.stack.imgur.com/ZZsAU.png

#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;
}

I have corrected the code like this.我已经更正了这样的代码。 Lines 1, 2 and 3 was the problem I think.第 1、2 和 3 行是我认为的问题。 While changing those lines as shown above code no longer runs to segmentation fault.在更改如上所示的那些行时,代码不再运行到分段错误。

NB : Don't use scanf for user input.注意:不要将scanf用于用户输入。 If you use scanf at all, always check its return value.如果您完全使用scanf ,请始终检查其返回值。 scanf %s is a bug: It can't prevent buffer overflows from longer input. scanf %s是一个错误:它无法防止较长输入引起的缓冲区溢出。

This could be another approach:这可能是另一种方法:

#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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM