The compiler optimizes the code in fun2 .
If you come back &a , it is optimized int b; . If you come back &b , it is optimized int a; . If you add some dummy calculations, you will see that the addresses of the returned values will be different.
int * fun2() { int a; int b; int* p = &a; p = &b; return p; }
Change main to print the return values of fun1 and fun2 .
int main () { int *ptr; ptr = fun1(); printf ("ptr = %p, fun1() called...\n", ptr); ptr = fun2(); printf ("ptr = %p, fun2() called...\n", ptr); printf ("*ptr = %d, fun2() called...\n", *ptr); return 0; }
When I run this code, I get the following output:
ptr = 0x7ffff98c70ec, fun1 () called ...
ptr = 0x7ffff98c70e4, fun2 () called ...
* ptr = 32749, fun2 () called ...
source share