为什么 gcc 在返回指向局部变量的指针而不是返回局部变量时会抛出警告? [英] Why does gcc throw a warning when returning a pointer to a local variable and not when returning a local variable?

查看:17
本文介绍了为什么 gcc 在返回指向局部变量的指针而不是返回局部变量时会抛出警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的代码示例.fun_ret_loc_ptr() 函数中的语句return (&i) 返回警告:函数返回局部变量的地址".另一方面,函数 fun_ret_loc_var() 中的语句 return a 并没有这样做.

Please see the code sample below. The statement return (&i) in function fun_ret_loc_ptr() returns a warning:"function returns address of local variable". On the other hand the statement return a in function fun_ret_loc_var() doesn't do so.

#include <stdio.h>
int* fun_ret_loc_ptr()
{
   int i = 10;
   return (&i);
}

int fun_ret_loc_var()
{
   int a = 20;
   return a;
}

int main()
{
   printf("val frm local ptr = %d
", *fun_ret_loc_ptr());
   printf("val frm local var = %d
", fun_ret_loc_var());
}

我知道在第一个函数中,返回的地址 (return (&i);) 引用了一个内存位置,该内存位置是对应于函数 fun_ret_loc_ptr() 的堆栈帧的一部分.一旦此函数返回堆栈帧(激活记录)将被销毁.同样的事情应该适用于函数 fun_ret_loc_var() 中的变量 'a' (return a;).即使返回了,但在main中使用时,'a'对应的内存也会死掉.

I understand that in the first function the address returned (return (&i);) refereed to a memory location that was part of the stack frame corresponding to function fun_ret_loc_ptr(). Once this function returned the stack frame (Activation Record) would be destroyed. Same thing should be applicable to the variable 'a' (return a;) in function fun_ret_loc_var(). Even though it is returned, when it is being used in main, the memory corresponding to 'a' would have died.

return"语句的功能来看,为什么会出现这种差异?

From the perspective of "return" statement's functionality, why does this difference arise?

推荐答案

按值返回变量会复制它,因此从函数返回后使用它是安全的.

Returning a variable by value copies it, and it is therefore safe to use it after returning from the function.

返回对局部变量的引用(或指针)是不安全的(因为从函数返回后引用/指针不再有效).

Returning a reference (or a pointer) to a local variable is not safe (because the reference / pointer is no longer valid after returning from the function).

现在,如果程序似乎按照您的预期进行,那纯属巧合.这称为未定义行为.事实上,结果可能是任何事情(从你的汽车爆炸到为接下来的三周精心准备午餐.只是未定义)

Now, if the program seemed to do what you expect, that is pure coincidence. This is known as Undefined Behaviour. In fact, the result may be anything (from your car blowing up to carefully making lunch for the coming three weeks straight. It is just undefined)

这篇关于为什么 gcc 在返回指向局部变量的指针而不是返回局部变量时会抛出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆