我需要分析以下程序的输出:
#include "stdio.h"
void foo(int **const p)
{
int j = 11;
*p = &j;
printf("%d ", **p);
}
int main()
{
int i = 10;
int *p = &i;
foo(&p);
printf("%d ", *p);
printf("%d ", *p);
}
我知道实际上没有人这样写,但尽管如此。我预计它会输出类似 11 [garbage] [garbage]
的内容,才发现答案是11 11 [undefined value]
。我决定旋转一下。
#include "stdio.h"
void foo(int **p)
{
int j = 11;
*p = &j;
printf("1:-");
printf("%d-", **p);
}
int main()
{
int i = 10;
int *p = &i;
foo(&p);
/* printf("2:-"); */
printf("%d-", *p);
printf("3:-");
printf("%d-", *p);
}
这将给出 1:-11-11-3:-0-
在我的平台上(macOS 10.12.2,在 Apple LLVM 版本 8.0.0 (clang-800.0.42.1) 和 Homebrew gcc 6.2.0 上进行了测试)。
如果我取消注释 printf("2:-");
我会得到 1:-11-2:-0-3:-0-
线。第二次调用打印 p
不同。同样,两个编译器都会产生相同的结果。
这是我的问题:
原来的答案正确吗?它如何(不)正确?
为什么以及如何调用
printf
更改p
的内容?还是我没捕获要点?
最佳答案
指针的值是不确定的,并且引用该对象会调用未定义的行为,根据 6.2.4p2 对象的存储持续时间:
[...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.
关于c - 指向范围外变量的指针在 C 中如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226038/