(我认为这个问题在技术上与 Can a local variable's memory be accessed outside its scope? 不同,因为它是 C 而不是 C++。)
我知道在 C 中你可以把一个局部变量放在一个 block 中,它的作用域将是那个 block :
#include <stdio.h>
int main() {
{
int x = 5;
printf("x = '%d'\n", x);
}
// can't see x anymore
}
我的问题是,在函数结束之前使用该内存仍然安全吗?从设计/编码实践的角度来看,它是否是 WISE 是一个单独的问题,但它是未定义的行为还是我可以指望该内存保持不变?例如:
#include <stdio.h>
int main() {
int *ptr;
{
int x = 5;
printf("x = '%d'\n", x);
// hold on to a ptr while we still know the address
ptr = &x;
}
// can't see x anymore, but is this safe?
printf("still have a ptr! '%d'\n", *ptr);
}
谢谢!
最佳答案
C99,6.2.4 p2 标准说:
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 是否会重用本地 block var 的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224748/