我可以返回指向 main 函数的本地指针吗? [英] Can I return local pointer to main function?

查看:69
本文介绍了我可以返回指向 main 函数的本地指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数 f() 来返回指向 main 函数的本地指针.我知道 f() 函数的内存会在它执行后被释放.但是 f() 函数可以返回指向 a[2] 数组的指针.我认为 a[2] 应该被释放,但它仍然存在.

I write a function f() to return local pointer to main function. I know the memory of f() function will be released after it execute. However the f() function can return the pointer which point the array of a[2]. I think a[2] should be released, but it still exist.

所以我想知道能不能写一个函数可以返回局部指针,局部指针指向函数中的局部变量?如果可以返回,为什么在 f() 函数结束后不释放 a[2] 的数组?

So I want to know can I write a function which can return the local pointer and the local pointer point the local variable in the function? If it can return, why array of a[2] would not be released after the end of f() function?

#include <stdio.h>

int* f()
{
  int a[2] = {1, 2};
  int* p = a;
  printf("%p\n", p);
  return p;
}

int main(void)
{
  int* p = f();
  printf("%p\n", p);
  return 0;
}

推荐答案

由于您指向的数组将超出范围并不复存在,尝试取消引用返回的指针将导致 未定义行为.

Since the array you point to will go out of scope and cease to exist, attempting to dereference the returned pointer will lead to undefined behavior.

然而,在实践中,内存仍然存在,如果后面的函数调用没有覆盖任何内容,它仍然不会被修改.因此,如果您尝试取消引用指针,您仍然会看到数据.但是你不应该那样做!

However, in practice the memory will still exist, and if none of the contents have been overwritten by later function calls, it will still be there unmodified. So if you attempt to dereference the pointer you will still see the data. But you should not do that!

关于你在做什么,你实际上并没有取消引用指针,所以你没有有 UB.您所做的只是打印指针本身的值.

Regarding what you're doing, you're not actually dereferencing the pointer, so you don't have UB. All you're doing is printing the value of the pointer itself.

这篇关于我可以返回指向 main 函数的本地指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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