memory allocation for local variable in C

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("%dn", *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.

  • In what memory segment this variable i in foo() gets store? or where does all local variables of functions get stores?
  • How can I access this from another function?

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

    链接地址: http://www.djcxy.com/p/36338.html

    上一篇: 内存管理:范围和本地指针变量

    下一篇: C中局部变量的内存分配