我有这个程序:
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对象的存储持续时间)
- ... 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/