Returning an address of local variable behaviour [duplicate]

一个人想着一个人 提交于 2019-12-02 22:39:30

问题


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

input:

#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();
}

Output:

13 -1077824828 -1077824828

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?


回答1:


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".

This is the address you 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.




回答2:


Calling printf creates a new stack frame that overwrites the location previously occupied by a.



来源:https://stackoverflow.com/questions/12414746/returning-an-address-of-local-variable-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!