Why my computer crashes when I execute this code in c?

时间:2016-08-31 17:27:42

标签: c

I was practicing about structs in C, so I've tried to execute 2 times this code and twice the computer crashes. I've had turn off the computer twice since my computer crashes.

Compiler is GCC (About MinGW on windows platform). The code is following :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct person {
    char name[50];
    int age;
    int document;   

};

int main(void){
    struct person p1;
    printf("Data of the  first person\n\n");
    printf("age:  ");
    fflush (stdin);
    scanf("%i",p1.age );
    printf("Document:  ");
    fflush(stdin);
    scanf("%i",p1.document);

    printf("Age is: %i and document is: %i ",p1.age,p1.document);
    return 0;
}

Sincerely, NIN.

UPDATE....

Bad news. Now Avast says I`ve created a virus. Therefore Avast delete my exe:

enter image description here

Should I report as false positive or not ?

1 个答案:

答案 0 :(得分:6)

scanf("%i",p1.age );

When you call scanf, p1.age is an integer with no particular value. So you are asking scanf to store the value you input in no particular place. It's not surprising this causes a crash. You want:

scanf("%i", &p1.age );

This tells scanf to read in an integer and store it at the address of p1.age.

It's surprising your compiler didn't give you a warning. Are you sure you have all of its warnings enabled?

When I try to compile this, I get appropriate warnings:

warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]

Update: Your anti-virus has heuristics that block software that has suspicious behavior. Your code has bugs, and your anti-virus doesn't know that they're just mistakes and not attempts to do something nefarious. It sounds like you don't have a very good environment set up for experimentation. Let me guess -- you're doing all this from a Windows administrator account.