0

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
Scope vs life of variable in C

int *p;

void foo()
{
    int i = 5;
    p = &i;
}

void foo1()
{
    printf("%d\n", *p);
}

int main()
{
   foo();
   foo1();
   return 0;
}

Output: 5 (foo1() print the value of i)

Note: I am running this program on Linux

According my knowledge, the scope of local automic variables are limited to the life of block/function.

  1. In what memory segment this variable i in foo() gets store? or where does all local variables of functions get stores?
  2. How can I access this from another function?
Community
  • 1
  • 1
beparas
  • 1,927
  • 7
  • 24
  • 30
  • 1
    This has been asked very often already, please search the site before posting. Also your use the buttons that you find on the top of the edit pane to structure your question, as you can find it now after chris' edit. Please invest at least a little bit of work before asking. – Jens Gustedt Jul 25 '12 at 06:30

1 Answers1

2

You're invoking undefined behaviour when accessing *p in foo1(). If you added a function like this:

void do_very_little(void)
{
    char buffer[] = "abcdef";
    puts(buffer);
}

and call it between calling foo() and foo1(), you probably get a different output. That's not guaranteed; one of the interesting things about undefined behaviour is that anything can happen and you've no grounds for complaint.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278