0

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?

Community
  • 1
  • 1
Nizarazo
  • 139
  • 2
  • 10

2 Answers2

1

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

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
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.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
  • why would printf pass parameters to the stack? aren't they sent to stdout buffer directly? – Nizarazo Sep 13 '12 at 21:32
  • No they are not and it is important: compiler which is producing the caller code, must not know what "printf" means, and in particular what this function is going to do - like working with stdout. – Pavel Radzivilovsky Sep 14 '12 at 21:41