指针 return 类型总是需要在堆上分配吗?

Do pointer return types always needs to be allocated on heap?

我是 C++ 新手,目前正在学习堆和堆栈。在我们的 class 中,我们有一个像这样的有问题的函数

int* Problematic(int capacity) {
     int data[capacity];
     // do something
     return data;
}

我知道这不会 return 除了悬空指针(是吗?),因为堆栈将在函数完成执行时释放函数中的所有内容。我的问题来了:

  1. 所有 return 类型是指针但它们在堆栈上 运行 的函数都会发生这个问题吗?(因为它们只是 return 一个地址和堆栈删除每个函数完成后的事情 运行)?
  2. 除了连接栈和堆(比如指向堆上的地址)之外,指针还能做些什么吗?
  3. 根据我的理解,stack和heap的区别在于,stack不是程序员手动分配内存,而是系统不断地自动stack分配内存。所以我想知道我是否有这样的功能 int ReturnInt() {const int a = 5;return a;} 这个函数returns到底是什么,如果它returns是一个地址,不会像之前那样把5栈删掉?如果这个函数 return 是一个整数 5,如何在内存中解释这个整数,因为它只是在 RAM 中添加 4 个字节并且内存地址仍然发生变化?

非常感谢您的帮助:)

Will this problem happened to all the functions which their return type is a pointer but they are running on stack?(Since they just return an address and stack delete every thing when the function finished running)?

是的,如果它们 return 指向函数堆栈上分配的内容的指针。

Is there any other functions that pointer has besides connecting stack to heap(Pointing a address on heap)?

当然可以。例如,从堆中分配的一个对象可能包含指向在堆上分配的另一个对象的指针。

From my understanding, the difference between stack and heap is that for stack, instead of manually allocating memory by programmer, stack allocating memory automatically by system continuously. So I am wondering if I have a function like this int ReturnInt() {const int a = 5;return a;} what actually this function returns, if it returns an address, won't stack deleted the 5 as before? If this function returns an integer 5, how to explain this integer in memory since it just add 4 bytes in RAM and changes still happens in memory address?

它 return 不是地址。它的 return 类型是 int 并且 return 是整数值 5,根本不是任何地址。函数 return 的 value 5. 没有要求实现将 5 存储在内存中,它可能会也可能不会按照它的意愿这样做。例如,它可以 return 寄存器中的值 5。

  1. 绝对。如果函数 return 指向分配在其堆栈上的数据的指针,则堆栈在函数退出后变为无效,指针将指向无效位置。

  2. 问题不清楚

  3. 堆栈是内存中的一个space,分配给函数内部使用。它被保留用于函数调用,并在函数 returns 之后被释放用于任何其他用途。在您的示例 int ReturnInt() {const int a = 5;return a;} 中没有指针。结果是 return 按值计算的。换句话说,变量 a 的值被复制到函数 return 值在其 return 之前的位置。这会保留值并允许在函数 return 之后使用它。下面的指针将工作:int *ReturnIntPtr(){int a = 5; return &a;}。这里你 return 指向堆栈的指针在 return.

    之后无效
  1. 是的。返回本地 non-static 地址没有什么价值。这样的 returned 地址不能用于解除引用。您仍然可以 printf("%p\n",(void*)the_address) 它们,但这就是您可以用它们做的所有事情。 (不过,返回本地 static 的地址是有道理的。这样的 returned 本地地址可以安全地取消引用。)

  2. 指针可以指向任何东西:全局变量、静态变量,并且它们可以从调用者传递(例如调用者可以在堆栈上分配它们的目标)。

  3. int ReturnInt(){const int a = 5;return a;} returns 通过大多数平台上的寄存器。如果那不可能,编译器将确保调用者具有 stack-allocated space 作为 return 值。

#2 问题(不清楚,但有机会)

您还有第三个存储 space 选项 - 静态。这是由你在编译时要求的内容决定的固定大小

  #include<stdio.h>
  char buffer[500];
  ...
  int main(int argc, char**argv){
  }

buffer 是静态分配的 500 字节