c - 为什么 c 不替换 *b?

标签 c scope undefined-behavior lifetime

我有这个程序:

    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.

关于c - 为什么 c 不替换 *b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807550/

相关文章:

c++ - 未定义的行为或 gcc 优化错误

c - 为什么 GCC 包含一个 "empty"XOR

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - c中的哈希表更新值

c++ - 错误 : ' ' was not declared in this scope

swift - 在嵌套函数中使用闭包如何逃逸?

javascript - 在 Javascript 中跨不同范围访问变量

c - 两个不同的 for 循环之间的 Printf 不起作用

c - c 代码中的段错误需要帮助

c - 使用递归反转数组内容(C语言)