c - 指向范围外变量的指针在 C 中如何表现?

标签 c pointers printf

我需要分析以下程序的输出:

#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不同。同样,两个编译器都会产生相同的结果。

这是我的问题:

  1. 原来的答案正确吗?它如何(不)正确?

  2. 为什么以及如何调用 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/

相关文章:

c - 错误 : field ‘nm_creds’ has incomplete type

c++ - C/pp 套接字,recv()/send() 仅在 gdb 下有效

c - 为什么这个 printf 语句需要一个符号?

c - 以色带为输入计算电阻值

c - 将一维数组插入 C 中的二维数组

c - void *的双指针和单指针?

pointers - 在 Rust 中有效地写入多个字节

c - 使用指针将 2 个矩阵相加

c++ - 如何让 CUDA 的 printf 打印到任意流?

C++ 相当于 sprintf?