C中局部变量的返回地址 [英] Return address of local variable in C

查看:16
本文介绍了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;
}

我没有收到第一个警告(例如 函数返回局部变量的地址)但我知道这是非法的,因为 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.

您正在返回 int * temp 的值.即使这个变量可能(并且在这个例子中是)包含一个值,该值是一个局部变量的地址,编译器也不会向上代码执行堆栈来查看是否是这种情况.

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.

注意:这两个片段同样糟糕,即使您的编译器没有警告您前者.不要使用这种方法.

<小时>

将地址返回给局部变量时应始终小心;通常,您可以说您从不应该这样做.

static 变量是一个完全不同的情况,在 这个线程.

static variables are a whole different case though, which is being discussed in this thread.

这篇关于C中局部变量的返回地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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