遇到分段错误错误 [英] Got stuck with Segmentation Fault Error

查看:79
本文介绍了遇到分段错误错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 c 编写一个简单的程序,但遇到了这个错误

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

分段错误(核心转储)

我知道 Segmentation fault 错误是由于内存访问冲突而发生的.但我无法弄清楚在下面的简单程序中哪里发生了错误的内存访问.

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.

推荐答案

您必须将指针传递给 int 而不是 int 本身.改成

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

在您的代码中,scanf() 假设 int 中的值是它必须写入的地址,从而导致未定义行为.此外,未定义行为的另一个原因是 a 在调用 scanf() 之前没有初始化,但这无关紧要,因为无论如何 未定义行为 正在发生发生.该标准规定,任何传递给 scanf() 的意外类型参数都将导致未定义行为.

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.

a 在调用 scanf() 之前没有被初始化的事实意味着如果你忽略 scanf() 的返回值并且它失败,并且您尝试读取代码中的 printf() 中的 a,您的代码将调用 未定义行为.这就是为什么检查返回值如此重要的原因.

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.

& address of 操作符生成一个包含其操作数地址的指针,scanf() 需要一个指向参数的指针1 以便能够将结果存储在其中.

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.

注意,例如,当将一个数组,一个 char 数组传递给 scanf() 一个带有 "%s" 说明符的字符串时,您不应该使用 & 运算符,因为数组名称被转换为指向自身第一个元素的指针,这正是 scanf() 在这种情况下所需要的.

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.

1注意,,所以这是改变scanf()函数内参数的唯一方法.

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.

这篇关于遇到分段错误错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆