I'm trying to gain a deeper understanding of C and would like clarification of the auto storage class.
So an auto variable has a duration of automatic, so it stops existing at the end of the block it is called in.
This code:
int main(void){
char* name;
name=return_name();
printf("Name is: %s\n Addr is: %p\n", name,name);
return 1;
}
char* return_name(void){
char* n="Waldo";
printf("Name is: %s & Addr is: %p\n", n,n);
return n;
}
Would output something like so:
Name is: Waldo & Addr is: 0xABCDEF
Name is: Waldo & Addr is: 0xABCDEF
So the variable n is forgotten, but the address is remembered through name. The data at the address is left untouched.
However, I read somewhere that after the function call ends since the variable duration was automatic; the memory address is released back to the program and it could potentially be overwritten by the program later? So if you want that address to remain reserved you would have to declare n with static.
I can't seem to find the source where I read this and I just want to be certain.
Thanks
EDIT: I didn't mean to recursively call return_name in return_name. I removed the line name=return_name in that function.