I am trying to understand the behavior of printf in this example. of course the main issue here is that we are returning a pointer to a value on the stack that was popped after the function Boo returned.
I compiled with gcc. In test1: I got 7 printed twice which was expected. And a garbage value on the second printf in test2. but when I compiled with gcc -O3 I got 0 printed on both cases and a compiler warning about returning address of local variable.
test.c: In function ‘Foo’: test.c:8:12: warning: function returns address of local variable [-Wreturn-local-addr] return t; ^ test.c:5:9: note: declared here int j;
Can someone help me explain how does the behavior of printf that causes this behavior?
int *Boo(int i, int *p)
{
int j;
int *t = &j;
*t = i + *p;
return t;
}
void Foo(int x)
{
if (x == 0) { return;}
Foo(x - 1);
}
//test1
int main(void)
{
int x = 5;
int *t = Boo(2, &x);
printf("%d", *t);
printf("%d", *t);
return 0;
}
//test2
int main(void)
{
int x = 5;
int *t = Boo(2, &x);
printf("%d", *t);
Foo(8);
printf("%d", *t);
return 0;
}