Is the following function safe, to return a pointer to a local variable?
int * foo(void)
{
int a = 6;
int *p = &a;
return p;
}
if not, at what conditions? if yes, how the safety is guaranteed by the compiler?
Test cases tried:
int * foo(void)
{
int a = 6;
int *p = &a;
return p;
}
int * bar(void)
{
int b = 7;
int *p = &b;
return p;
}
int main()
{
int a = *foo();
int b = *bar();
printf("%d, %d, %d\n", 1, 2, 3); //to mess up stack
printf("%d, %d\n", a, b);
return 0;
}
it will successfully print "6, 7". However with -O2 it prints "0, 0"