Returning an address of local variable behaviour [

2020-05-01 06:35发布

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?

2条回答
贪生不怕死
2楼-- · 2020-05-01 07:03

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.

查看更多
迷人小祖宗
3楼-- · 2020-05-01 07:16

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

查看更多
登录 后发表回答