一旦超出范围,C会重用本地块var的内存吗? [英] Will C reuse the memory of a local block var once it goes out of scope?

查看:46
本文介绍了一旦超出范围,C会重用本地块var的内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我相信这个问题在技术上不同于可以访问局部变量的内存吗?,因为它是C而不是C ++.

(I believe this question is technically distinct from Can a local variable's memory be accessed outside its scope? because it is C instead of C++.)

我知道在C语言中,您可以将局部变量放在一个块中,并将其范围限定在该块中:

I know that in C you can put a local variable in a block and it will be scoped to that block:

#include <stdio.h>
int main() {
    {
        int x = 5;
        printf("x = '%d'\n", x);
    }
    // can't see x anymore
}

我的问题是,在功能结束之前使用该内存是否仍然安全?从设计/编码实践的角度来看,它是否是WISE是一个单独的问题,但是它是未定义的行为,还是我可以指望这种持久的存储方式?例如:

My question is, is it nonetheless still SAFE to use that memory until the end of the function? Whether it is WISE from a design / coding practices perspective is a separate question, but is it undefined behavior or can I count on that memory staying put? For example:

#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标准说:

The C99, 6.2.4 p2 standard says:

如果在生命周期之外引用了一个对象, 行为未定义.指针的值变为 不确定它所指向的对象何时到达其终点 一生.

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会重用本地块var的内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆