c - 一旦超出范围,C 是否会重用本地 block var 的内存?

标签 c memory memory-management scope

(我认为这个问题在技术上与 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/

相关文章:

c - 正确释放分配的虚拟内存

c - 删除数组中的元素并向左移动元素以缩小间隙

c - 如何在每个节点上增长四叉树

c - AVR 编程 - 如何在 C 中读取连续的按钮按下

c - 为什么 ELF 中外部变量的大小为 0?

Javascript 私有(private)方法——内存影响是什么?

c++ - 从函数返回后删除动态数组

debugging - GDB 6.3 在单步执行代码时给出 "Cannot access memory at address 0x<32bitval>"

c - 在 C 中的行尾后读取问题

javascript - PhoneGap 内存管理