Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I’m trying to understand why I get this output for the below program
[hello] [0xbfde68f4]
[world] [0xbfde68f4]
[world] [0xbfde68f4]
The program is
int main(void)
{
char **ptr1 = NULL;
char **ptr2 = NULL;
ptr1 = func1();
ptr2 = func2();
printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);
printf(" [%s] [%p]\n",*ptr2, (void*)ptr2);
printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);
return 0;
}
char** func1()
{
char *p = "hello";
return &p;
}
char** func2()
{
char *p = "world";
return &p;
}
I understand that it’s not a good practice to return address of local variables but this is just an experiment.
The memory address is re-used. First it holds the address of the constant holding “hello”, then it is re-used to hold the address of the constant holding “world”.
Once memory is no longer in use, it is available for re-use. It’s generally most efficient to re-use the most recently used memory, so that’s what compilers and memory managers typically try to do.
Note that it’s definitely not guaranteed. You may find that this program crashes or gives different addresses on different compilers or platforms. However, re-use is very, very likely in this particular scenario, since both variables are local and assigned on the stack and no intervening code uses any stack space. If you add an intervening use of stack space, you will get different behavior.