Say I have the following two functions:
1
int * foo()
{
int b=8;
int * temp=&b;
return temp;
}
2
int * foo()
{
int b=8;
return &b;
}
I don't get any warning for the first one (e.g. function returns address of a local variable) but I know this is illegal since b
disappears from the stack and we are left with a pointer to undefined memory.
So when do I need to be careful about returning the address of a temporary value?
The reason you are not getting a warning in the first snippet is because you aren't (from the compiler's perspective) returning an address to a local variable.
You are returning the value of int * temp
. Even though this variable might be (and in this example is) containing a value which is an address of a local variable, the compiler will not go up the code execution stack to see whether this is the case.
Note: Both of the snippets are equally bad, even though your compiler doesn't warn you about the former. Do not use this approach.
You should always be careful when returning addresses to local variables; as a rule, you could say that you never should.
static
variables are a whole different case though, which is being discussed in this thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With