Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
mary Avatar asked Jan 05 '12 13:01

mary


1 Answers

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.

like image 73
Filip Roséen - refp Avatar answered Oct 06 '22 00:10

Filip Roséen - refp