Got stuck with Segmentation Fault Error

折月煮酒 提交于 2019-12-31 05:20:10

问题


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

Segmentation Fault (Core dumped)

I know Segmentation fault error occurs due to memory access violation. But I'm unable to figure out where in the below simple program bad memory access is happening.

#include<stdio.h>
int main()
{
    int a = 0;   
    scanf("%d", a);
    printf("%d\n", a);
    return(0);
}

I'm compiling online here, In code blocks also it's giving the same error.


回答1:


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.




回答2:


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);
     ^


来源:https://stackoverflow.com/questions/34927803/got-stuck-with-segmentation-fault-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!