返回局部变量行为的地址 [英] Returning an address of local variable behaviour

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

问题描述

可能重复:
能否在其范围之外访问局部变量的内存? /a>

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

输入:

#include <stdlib.h>
#include <stdio.h>
int func2(void);
int* func1(void);

int func2(void)
{
    int* b;
    b = func1();
    printf("%d", *b);
    printf("%d", *b);
    printf("%d", *b);
}

int* func1()
{
    int a = 13;
    return &a;
}

int main()
{
    func2();
}

输出:

13 -1077824828 -1077824828

有人可以解释堆栈和操作系统中发生了什么吗?为什么在获得指针值后结果从13变为垃圾?

Can someone explain what happened in the stack and OS? Why the result changed from 13 to garbage after getting the value of the pointer?

推荐答案

好的. 结果将在调试和发布(清除)之间有所不同. 如果查看程序集,则局部变量为EBP-(有些偏移). 这就是说,在堆叠中更高",如更多"中一样.

Sure. The result will differ between debug and release (clean). A local variable is EBP-(some offset) if you look at the assembly. This means, HIGHER IN STACK, as in "further".

这是您返回的地址.

通常,如果函数刚刚返回,它将保持不变.在某些编译器上进行调试时,将有意将其丢弃,以帮助您更快地捕获悬空指针错误.现在,printf调用将重用堆栈中的相同地址以传递参数并传递其自身的局部变量(有一些局部变量).它们将被写入func1 return清空的地址,从而覆盖您获得的地址所指向的任何内容.

Normally it would be untouched if the function just returns. In debug build on some compilers, it would be garbaged on purpose to help you catch the dangling pointer error faster. Now, printf call reuses the same addresses in the stack to pass parameters and for its own local variables (it has some). They will be written to the address emptied by func1 return, thus overwriting whatever is pointed by the address you obtained.

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

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