在内存分配的上下文中堆栈到底是什么意思

编程入门 行业动态 更新时间:2024-10-28 16:24:15
本文介绍了在内存分配的上下文中堆栈到底是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我读了诸如在堆栈中分配内存"之类的东西,或诸如这些变量置于堆中"之类的东西.我曾经读过一本有关微处理器的书,可以淡淡地记得在所谓的堆栈上有主题或部分内容.而且我知道堆栈也意味着一种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) }

更多推荐

在内存分配的上下文中堆栈到底是什么意思

本文发布于:2023-10-08 14:16:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   到底是什么   文中   分配   内存

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!