Please see the code sample below.
The statement return (&i)
in function fun_ret_loc_ptr()
returns a warning:"function returns address of local variable". On the other hand the statement return a
in function fun_ret_loc_var()
doesn't do so.
#include <stdio.h>
int* fun_ret_loc_ptr()
{
int i = 10;
return (&i);
}
int fun_ret_loc_var()
{
int a = 20;
return a;
}
int main()
{
printf("val frm local ptr = %d\n", *fun_ret_loc_ptr());
printf("val frm local var = %d\n", fun_ret_loc_var());
}
I understand that in the first function the address returned (return (&i);
) refereed to a memory location that was part of the stack frame corresponding to function fun_ret_loc_ptr()
. Once this function returned the stack frame (Activation Record) would be destroyed. Same thing should be applicable to the variable 'a' (return a;
) in function fun_ret_loc_var()
. Even though it is returned, when it is being used in main, the memory corresponding to 'a' would have died.
From the perspective of "return
" statement's functionality, why does this difference arise?