局部变量的地址返回 [英] returning address of local variable

查看:92
本文介绍了局部变量的地址返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope\">Can一个局部变量的内存是它的范围之外访问?

我试图理解为什么我得到这个输出下面的程序

I'm trying to understand why I get this output for the below program

[hello] [0xbfde68f4]
[world] [0xbfde68f4]
[world] [0xbfde68f4]

该计划是

int main(void)
{
    char **ptr1 = NULL;
    char **ptr2 = NULL;

    ptr1 = func1();
    ptr2 = func2();
    printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);

    printf(" [%s] [%p]\n",*ptr2, (void*)ptr2);

    printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);

    return 0;
}

char** func1()
{
    char *p = "hello";
    return &p;
}

char** func2()
{
    char *p = "world";
    return &p;
}

据我所知,这不是一个很好的做法,返回局部变量的地址,但是这仅仅是一个实验。

I understand that it's not a good practice to return address of local variables but this is just an experiment.

推荐答案

内存地址重新使用。首先,它持有恒控股你好的地址,那么它被重新用来存放恒控股世界的地址。

The memory address is re-used. First it holds the address of the constant holding "hello", then it is re-used to hold the address of the constant holding "world".

在存储器是不再使用,它​​是可用于再使用。这是一般最有效的再利用最近使用的内存,所以这就是编译器和内存管理器通常会尝试这样做。

Once memory is no longer in use, it is available for re-use. It's generally most efficient to re-use the most recently used memory, so that's what compilers and memory managers typically try to do.

请注意,这是绝对不能保证。您可能会发现这个程序崩溃或给出了不同的编译器或平台不同的地址。然而,再利用是非常,在此特定情形的可能性很大,因为这两个变量是局部的,并分配在栈上,并没有介入code使用的堆栈空间。如果添加居间利用堆栈空间,你会得到不同的行为。

Note that it's definitely not guaranteed. You may find that this program crashes or gives different addresses on different compilers or platforms. However, re-use is very, very likely in this particular scenario, since both variables are local and assigned on the stack and no intervening code uses any stack space. If you add an intervening use of stack space, you will get different behavior.

这篇关于局部变量的地址返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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