用C返回局部变量的地址 [英] Return address of local variable in C
问题描述
说我有以下两个功能:
1
int * foo()
{
int b=8;
int * temp=&b;
return temp;
}
2
int * foo()
{
int b=8;
return &b;
}
我没有得到的第一个任何警告(比如函数返回一个局部变量的地址的),但我知道这是因为非法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.
您在返回整型值*温度
。尽管这个变量可能包含一个值,它是一个局部变量的地址是(在这个例子),编译器将不上浮code执行栈,看看是否属于这种情况。
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.
注意:这两个片段都同样糟糕,即使你的编译器不会警告你关于前者。不要使用这种方法。的
您应该返回到本地变量地址时,一定要加倍小心;作为一项规则,你可以说你的从不应
You should always be careful when returning addresses to local variables; as a rule, you could say that you never should.
静态
变量是一个完全不同的情况下,虽然,这是在<一个正在讨论href=\"http://stackoverflow.com/questions/453696/is-returning-a-pointer-to-a-static-local-variable-safe\">this螺纹。
static
variables are a whole different case though, which is being discussed in this thread.
这篇关于用C返回局部变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!