I know returning pointer to local variable is not a good idea, because the stack used for that variable will be reused. As so:
#include <stdio.h>
int *func(){
int x = 10;
return &x;
}
int main(){
printf("%p\n",(void*)func());
}
print (nil)
as expected.
However, why can I then return pointer to data of local struct? :
#include <stdio.h>
struct foo{
char c;
int *p;
};
int *func(){
struct foo f;
f.c = 'c';
int local = 10;
f.p = &local;
return f.p;
}
int main(){
int *b = func();
printf("%d\n",*b);
}
The struct foo f
is local in function func
so there should be the same rule for every local variable - that is automatic storage in stack. I have not yet looked at assembler output of it to confirm that, but if this assumption is not true, then why is there special treating for struct types? Before I look to asm, is the storage of struct foo in stack?