Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...