Got stuck with Segmentation Fault Error

后端 未结 2 1945
攒了一身酷
攒了一身酷 2021-01-27 15:40

I\'m writing a simple program in c and I\'m got stuck with this error

Segmentation Fault (Core dumped)

I know Se

相关标签:
2条回答
  • 2021-01-27 16:19

    You must pass a pointer to int instead of the int itself. Change it to

    if (scanf("%d", &a) == 1)
        printf("%d\n", a);
    else
        printf("Invalid input\n");
    

    In your code, scanf() is assuming that the value in the int is the address it has to write to, leading to undefined behavior. Also, another reason for undefined behavior is that a wans't initialized before calling scanf() but that is irrelevant since anyway undefined behavior was going to occur. The standard specifies that any parameter of unexpected type passed to scanf() will cause undefined behavior.

    The fact that a was not initialized before calling scanf() implies that if you ignore the return value of scanf() and it fails, and you try to read a like in the printf() in your code, your code will invoke undefined behavior. That's why it's so important to check the return value.

    The & address of operator makes a pointer containing the address of it's operand, scanf() needs a pointer to the parameter1 in order to be able to store the result in it.

    Note that when passing an array for example, a char array to scanf() a string with the "%s" specifier, you should not use the & operator because the array name is converted to a poitner to the first element of itself, which is what scanf() needs in that case.


    1Note, that there is no pass by reference in c, so this is the only way you can alter the parameter inside the scanf() function.

    0 讨论(0)
  • 2021-01-27 16:31

    Change

    scanf("%d", a);
    

    to

    scanf("%d", &a);
    

    scanf needs a pointer to a variable, not the value of a variable.

    I can suggest you to add -Wall option when you compile. In your case gcc will warn you:

    test.c: In function ‘main’:
    test.c:25:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
         scanf("%d", a);
         ^
    
    0 讨论(0)
提交回复
热议问题