C的未定义行为

时间:2015-11-09 14:06:48

标签: c function pointers

我有这段代码:

#include <stdio.h>
#include <math.h>
int *fun();
int main()
{
    int *t;
    t=fun();
    printf("%d\n",*t);
    printf("%d\n",*t);
}
int *fun()
{
    int r=95;
    return(&r);
}

此代码在codeblocks中显示的输出是

95
-2

我不明白为什么第二个printf()正在打印垃圾值。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:1)

这是UB,因为rfun()内的局部变量,如果你返回局部变量的地址并尝试在调用者中使用它,你最终会使用它过了它的一生。在C中,它被定义为UB。

FWIW,变量的地址并不总是等同于int,或者可以安全地转换为指针,因此它至少应为int *。在您的代码中,

t=fun();

return(&r);

应该给你警告!!

答案 1 :(得分:0)

  1. 您从int*返回fun,即使它已声明返回int。将声明更改为int* fun()

  2. An empty list allows a variable number of arguments。请改用int* fun(void);

  3. 未定义的行为是未定义的行为。您尝试access memory of a local variable from outside the function,因此可能会发生任何事情。从C标准的层面来看,它显然是 undefined ,无论是第一个,第二个还是没有声明都表现得很奇怪(比如“打印垃圾值”)。

相关问题