代码输出说明
Explanation for the output of the code
#include<stdio.h>
int *call();
int main()
{
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
return 0;
}
int * call()
{
int x=25;
++x;
return &x;
}
此代码的输出是 0。我期待 26。
有人可以解释一下原因吗?
我应该怎么做才能达到 26 岁?
这里的问题是,从 int * call()
开始,您正在 return 获取局部变量的地址,该地址在函数执行完成后变得无效。使用 return 值调用 undefined behavior.
你应该
- 获取一个指针,使用
malloc()
和 family 等内存分配器函数分配内存,然后 return 指针。
- 使用一个
static
变量的整个生命周期贯穿整个程序执行。
也就是说,不要使用 fflush(stdin)
,因为它会调用未定义的行为。引用 C11
,章节 §7.21.5.2,(强调我的)
If stream
points to an output stream or an update stream in which the most recent
operation was not input, the fflush
function causes any unwritten data for that stream
to be delivered to the host environment to be written to the file; otherwise, the behavior is
undefined.
当你创建这个函数并调用它时,一个函数帧被推入堆栈,其中有一个 space 用于在那里声明的 int 变量。现在您增加该值并尝试 return 地址。现在函数结束,栈帧被删除。您正在尝试阅读它。它会 return 一些随机的东西。啊,在它的意义上不是随机的,但它 returns 没有定义。你得到 0 ..有时可能会得到 1 或 23 或 128749 或 -7364184。
要获得 26,您可能需要使用堆中的一些东西。(或声明一个足够长的数组)。
分配足够大的内存来容纳一个整型变量。然后操纵它。 Return 指向那个的指针。你会看到你想看到的。
注意:这是未定义的行为....当您 运行 在不同的时间或不同的机器上时,它可能 return 其他东西。 :)
我在这里提到的这个堆和栈是特定于实现的。堆是指我们分配的动态内存。
您不应在 stdin
上使用 fflush()
,它对输入流有未定义的行为。 You can Read about it here.
返回局部变量的地址,在函数执行完成后变为无效将导致未定义的行为。
为了期待答案,我删除了 fflush(stdin)
并在 Windows 和 GCC 4.1.2 编译器上得到了输出 26
。
正如@Anjaneyulu 所评论的,它可能也依赖于编译器,但这是我在 windows.
上的测试截图
#include<stdio.h>
int *call();
int main()
{
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
return 0;
}
int * call()
{
int x=25;
++x;
return &x;
}
此代码的输出是 0。我期待 26。
有人可以解释一下原因吗?
我应该怎么做才能达到 26 岁?
这里的问题是,从 int * call()
开始,您正在 return 获取局部变量的地址,该地址在函数执行完成后变得无效。使用 return 值调用 undefined behavior.
你应该
- 获取一个指针,使用
malloc()
和 family 等内存分配器函数分配内存,然后 return 指针。 - 使用一个
static
变量的整个生命周期贯穿整个程序执行。
也就是说,不要使用 fflush(stdin)
,因为它会调用未定义的行为。引用 C11
,章节 §7.21.5.2,(强调我的)
If
stream
points to an output stream or an update stream in which the most recent operation was not input, thefflush
function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
当你创建这个函数并调用它时,一个函数帧被推入堆栈,其中有一个 space 用于在那里声明的 int 变量。现在您增加该值并尝试 return 地址。现在函数结束,栈帧被删除。您正在尝试阅读它。它会 return 一些随机的东西。啊,在它的意义上不是随机的,但它 returns 没有定义。你得到 0 ..有时可能会得到 1 或 23 或 128749 或 -7364184。
要获得 26,您可能需要使用堆中的一些东西。(或声明一个足够长的数组)。 分配足够大的内存来容纳一个整型变量。然后操纵它。 Return 指向那个的指针。你会看到你想看到的。
注意:这是未定义的行为....当您 运行 在不同的时间或不同的机器上时,它可能 return 其他东西。 :)
我在这里提到的这个堆和栈是特定于实现的。堆是指我们分配的动态内存。
您不应在 stdin
上使用 fflush()
,它对输入流有未定义的行为。 You can Read about it here.
返回局部变量的地址,在函数执行完成后变为无效将导致未定义的行为。
为了期待答案,我删除了 fflush(stdin)
并在 Windows 和 GCC 4.1.2 编译器上得到了输出 26
。
正如@Anjaneyulu 所评论的,它可能也依赖于编译器,但这是我在 windows.
上的测试截图