局部变量是否使用堆进行存储? [英] Do local variables use heap for storage?

查看:124
本文介绍了局部变量是否使用堆进行存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道函数调用期间是否使用堆来保存局部变量.谢谢.

I want to know if heap is used for holding local variables during function calls. Thank you.

推荐答案

全局变量存储在堆中,局部变量存储在栈中.

使用new关键字创建的对象将存储在堆中,因为它们将无限期保留.

在函数中创建的指针存储在堆栈中,而它们指向的对象或内存块则可以存储在堆或堆栈中.例如
Global variables are stored on the heap and local variables are stored on the stack.

Objects created by the new keyword are stored on the heap because they will stay their for an indefinite time.

Pointer created in a function are stored on the stack while the objects or memory blocks they point to might be stored on either the heap or the stack. e.g.
int a = 5;
int *b = &a;


"b"存储在堆栈上,并指向堆栈上的一个对象.而


''b'' is stored on the stack and points to an object on the stack. While

int *a = new int[6];


"a"存储在堆栈中,而其指向的数组存储在堆中.


''a'' is stored on the stack while the array it points to is stored on the heap.


除了CcoollzZ的答案外,您还可以参考 [
In addition to CcoollzZ''s answer, you can refer to this[^] for a detailed explanation on the subject.
Also have a look at this[^] thread. :)


当您没有显式使用newmalloc 或其他相关的内存分配函数时,将使用堆栈.

例如:

The stack is used when you do not use new or malloc or other related memory allocation functions explicitly.

For example:

int x;//<--- stack space is used.

int *x = new int();//<--- heap space is used. 




与函数调用,函数调用和传入的参数以及在函数内部声明的变量有关的所有信息都在堆栈上,除非您在堆上显式分配它们.




Relating to function calls, the function call, and the parameters passed in, and the variables declared inside the function are all on the stack unless you explicitly allocate them on the heap.

void myFunc(int x)
{
  int y;//<--- allocated on the stack
}



必须释放堆上分配的所有内容.对于C分配,请使用free,对于C ++分配,请使用deletedelete[]用于数组.

您还可以在这里找到我的答案,该答案给出了许多
更多堆栈和堆之间的差异.



Anything allocated on the heap must be freed. For C allocations use free, for C++ allocations use delete or delete[] for arrays.

You can also find my answer here which gives a lot more differences between the stack and the heap.


这篇关于局部变量是否使用堆进行存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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