在内存分配的上下文中堆栈到底是什么意思 [英] what exactly do stack and mean in context of memory allocation

查看:101
本文介绍了在内存分配的上下文中堆栈到底是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了诸如在堆栈中分配内存"之类的东西,或诸如这些变量置于堆中"之类的东西.我曾经读过一本有关微处理器的书,可以淡淡地记得在所谓的堆栈上有主题或部分内容.而且我知道堆栈也意味着一种LIFO类型的数据结构.

I read things like "memory is allocated in a stack " or things like "these variable are placed in a heap ". I had once studied a book on microprocessor and can faintly remember that there had been topics or sections on something called as stack . And I do know that stacks also mean a kind of LIFO type data structure .

因此,我对堆栈的含义感到困惑.除了被称为堆栈的寄存器以外,每个微处理器中是否都存在存储位置?

So , I feel confused as to what stacks imply . Are there memory locations in a every microprocessor other than the registers which are called as stack ?

推荐答案

我将介绍最常见的情况.

I'll describe the most common situation.

在这种情况下,堆栈是程序(更确切地说是线程)的专用内存.启动程序时,操作系统将自动分配此内存.通常(但不总是),堆栈是从主内存分配的(因此它不是CPU中的特殊内存).

In this context, stack is a dedicated memory for a program (more precisely, for a thread). This memory is allocated automatically by the operating system, when your program is started. Usually (but not always), stack is allocated from the main memory (so it is not a special memory in the CPU).

它的名称是stack,因为它使用的是"LIFO样式".调用函数时,将从堆栈中分配其局部变量(推入堆栈").返回时,将释放这些变量(从堆栈弹出").

It's name is stack, because it is used "LIFO style". When a function is called, its local variables gets allocated from the stack ("pushed to the stack"). When it returns, these variables are freed ("pop from the stack").

关于堆:堆是一个可以比堆更灵活地分配内存的地方.堆存储空间通常比堆栈大得多.而且,即使函数(分配了空间)返回后,分配的空间仍将可用.对于没有垃圾收集的语言,您必须手动释放分配的空间.请勿将此堆与数据结构堆混淆,这是完全不同的事情.

About heap: heap is the place from where one can allocate memory in a more flexible manner than stack. Heap storage space is usually much larger than the stack. And the allocated space will be available even after the function (which allocated the space) returns. And for languages which doesn't have garbage collection, you have to manually free the allocated space. This heap is not to be confused with the data structure heap, which is a completely different thing.

char *var;
void example(int length) {
  char stackVar[1024]; // a 1024 element char array allocated on the stack
  char *heapVar = new char[length]; // a length sized variable allocated on the heap, and a pointer (heapVar) to this place allocated on the stack

  var = heapVar; // store a pointer to the allocated space

  // upon return, stackVar is automatically freed
  //              the pointer heapVar automatically freed
  //              the space that heapVar points to is not freed automatically, can be used afterwards (via the var pointer)
}

这篇关于在内存分配的上下文中堆栈到底是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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