Return address of local variable in C
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.
i would say that you can return the local variable or rather pointers to such IF it was dynamically allocated by malloc, in that case the memory used for storing variable want be on stack but on heap and won't be cleared or re-used after exiting the function as it takes place in the case of automatic local variables (created without malloc), am i right?