为什么 c 不替换 *b?

Why doesn't c replace *b?

我有这个程序:

    int* b;
    {
        int a = 5;
        b = &a;
    } //a gets destroyed here
    {
        int c = 7; //c replaces a?
        printf("c: %d\n", c);
    }
    printf("*b: %d", *b); //*b is still 5

为什么 c 不替换 *b 或类似的东西?是不是因为一些编译器的优化(我是用clang编译的,但我试过一些在线编译器,结果还是一样)

程序有未定义的行为,因为指针 p 在该语句的范围内具有无效值

printf("*b: %d", *b);

并试图取消引用它。

指针具有无效(不确定)值,因为它未指向对象。指针早期指向的对象在此范围内不存在。

来自C标准(6.2.4对象的存储持续时间)

  1. ... 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 (or just past) reaches the end of its lifetime.