1
#include <stdio.h>

int main()
{
    int x=10;
    int *p=&x;
    foo(&p);
    printf("%d ",*p);
    printf("%d ",*p);
}
void foo(int** l)
{
    int j=20;
    *l=&j;
    printf("%d ",**l);
}

can you explain why the output is [20 20 garbage] ? why cant i get 20 20 20? Both the statements of print after the foo function call are same.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 6
    The only output of your program that is *not* garbage is the first 20. The second 20 printed by your program is undefined behavior, i.e. garbage that happens to look like 20. – Sergey Kalinichenko Sep 14 '17 at 17:05
  • 1
    Because dereferencing a pointer pointing to a variable that is out of scope is Undefined Behavior. – Ajay Brahmakshatriya Sep 14 '17 at 17:07
  • so, why my second output is not 20? I am just trying to dereference my pointer variable p. – Sirish Potnuru Sep 14 '17 at 17:07
  • how can my pointer p be out of scope? can you bring more detailed answer? – Sirish Potnuru Sep 14 '17 at 17:09
  • 1
    you also didn't declare the `foo` function – phuclv Sep 14 '17 at 17:14
  • @SirishPotnuru You have gone to some lengths to make `p` point to `l`, which is a *local variable* within the function `foo`. An essential property of local variables is that they disappear when the function containing them returns. Typically they're stored on the stack, which means that the value may stay there for a little while -- until some later function call reuses that portion of the stack and obliterates it. – Steve Summit Sep 14 '17 at 17:38
  • Thanks that really helped – Sirish Potnuru Sep 15 '17 at 00:51

0 Answers0