简体   繁体   English

C-返回局部指针与局部变量

[英]C - Returning a local pointer vs local variable

My question is regarding these two cases: 我的问题是关于这两种情况:

#include <stdio.h>
int *foo1();
int *foo2();

int main()
{
   printf("so it's %d\n",*foo1());
   printf("so it's %d\n",*foo2());
}

int *foo1()
{
   int i1 = 5;
   return &i1;
}

int *foo2()
{
   int i2 = 5;
   int *p = NULL;
   p = &i2;
   return p;
}

case1: When its the case with foo1(), we get an error because we are trying to return a copy of address to main whose data has been deleted(when we exit foo1() function) case1:如果是foo1(),则会出现错误,因为我们试图将地址的副本返回到已删除数据的main中(退出foo1()函数时)

case2: But in foo2() , it doesn't give an error though we are returning a copy to a pointer of local variable whose data will be deleted after we exit the foo2() function, why is it so? 情况2:但是在foo2()中,虽然我们将返回的副本返回到局部变量的指针,但是在退出foo2()函数后其数据将被删除,但它没有给出错误为什么会这样呢?

TL;DR: why foo2() doesn't give an error but foo1() does? TL; DR:为什么foo2()没有给出错误但foo1()却给出了错误?

TIA. TIA。

The behaviour of both functions foo1 and foo2 are undefined , in both C and C++. 在C和C ++中,函数foo1foo2的行为均未定义

You are not allowed to dereference a pointer that points to a variable with automatic storage duration that's no longer in scope. 不允许取消引用指向变量的指针的指针,该变量具有自动存储持续时间,而该持续时间不再在范围内。

Tomorrow, foo2() may well give you an error too. 明天, foo2()也可能会给您一个错误。 Or the compiler might eat your cat. 否则编译器可能会吃掉你的猫。

In both cases, you are invoking undefined behavior by returning a pointer to a local variable and dereferencing it. 在这两种情况下,您都通过返回指向局部变量的指针并对其取消引用来调用未定义的行为

Invoking undefined behavior does not mean you will always crash. 调用未定义的行为并不意味着您将永远崩溃。 It means the behavior of the program is undefined. 这意味着程序的行为是不确定的。 It could crash, it could output strange results, or it could appear to work properly. 它可能会崩溃,它可能会输出奇怪的结果,或者它似乎可以正常工作。 As you have seen, this behavior manifests itself in two of these ways in your program. 如您所见,此行为在程序中以两种方式表现出来。

Making a seemingly unrelated change, such as adding an unused local variable or a printf for debugging, can change the way undefined behavior manifests itself. 进行看似无关的更改(例如添加未使用的局部变量或用于调试的printf可能会更改未定义行为的显示方式。

Both are undefined behavior, you cannot rely on the compiler giving you warnings for undefined behavior. 两者都是未定义的行为,您不能依赖编译器为未定义的行为提供警告。

You are essentially doing the same thing in both functions and in fact both might result in the same assembly code to be generated. 本质上,您在这两个函数中都执行相同的操作,并且实际上,两者都可能导致生成相同的汇编代码。

case1和case2的行为均未定义,您无法将指针返回给局部变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM