Reputation: 440
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?
Upvotes: 1
Views: 1405
Reputation: 215241
Functions don't return variables; they return values. Whether the value came from a local variable is irrelevant; even if it didn't, it came from a "local expression" (my term) whose lifetime is even shorter than that of a local variable. The problem with returning a pointer to a local (assuming it's automatic, not static) variable is that the value of the pointer is invalid and any use of it after the function returns results in undefined behavior.
Upvotes: 0
Reputation: 37437
You can think of an analogy with passing arguments by value or by reference.
Here, you return the value by reference, or by value. If you return the value by value, then the value is available in the caller. If you return the value by reference, then the reference of the value is returned to the caller. To access the value, the caller has to dereference, but the reference does not point to any valid value anymore.
Upvotes: 1
Reputation: 62439
You covered the explanation pretty well at the end of your post. Your only "mistake" is saying that the variable a "dies" at the end of the function call. Indeed it does die, but a copy of a is returned, not the a from the function stack. Therefore, there is no problem in accessing the return value of that function.
Upvotes: 2
Reputation: 392931
Returning a variable by value copies it, and it is therefore safe to use it after returning from the function.
Returning a reference (or a pointer) to a local variable is not safe (because the reference / pointer is no longer valid after returning from the function).
Now, if the program seemed to do what you expect, that is pure coincidence. This is known as Undefined Behaviour. In fact, the result may be anything (from your car blowing up to carefully making lunch for the coming three weeks straight. It is just undefined)
Upvotes: 6