- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 329字
- 2021-07-02 23:07:26
What is meant by the stack?
The simplest way to think about the stack is to consider memory as a series of boxes. For these examples, think of the boxes in groups of four: the function name, the address, the variable name, and the value. Here's a main function with a single local variable:
fn main() { let i = 32; }
The stack boxes will look like this:

A slightly different example is as follows:
fn second() { let a = 32; let b = 12; } fn main() { let d = 100; }
Here, we will have two unconnected stack boxes. Since the second function is never called, we never actually allocate memory on the stack for it. The memory allocations are therefore exactly same as in the first example.
Our third example is where we have the main function call to the second function; in this case, we actually reserve memory for the second function:
fn second() { let a = 32; let b = 12; } fn main() { let d = 100; second(); }
In terms of our stack boxes, we have the following:

The variable from the main function has the address of 0 as it is from the top frame-the frame that calls the other function. The value for the address is purely for this example; it can be anywhere and, typically, different types require a different amount of the stack to hold them. For instance, if the number type is 4 bytes in length, the address will be the base address of the stack to store d, then the address + 4 for b, and finally the address + 8 for a.
Once foo has returned, the stack reverts to this:

As soon as the main function has finished, the stack is empty.
This stacking continues for as many different functions as the application has, and they always work in the same way.
- UI設(shè)計(jì)基礎(chǔ)培訓(xùn)教程
- 造個(gè)小程序:與微信一起干件正經(jīng)事兒
- 軟件測(cè)試工程師面試秘籍
- Servlet/JSP深入詳解
- 單片機(jī)應(yīng)用技術(shù)
- The Data Visualization Workshop
- Ext JS 4 Plugin and Extension Development
- Mastering SciPy
- Spark技術(shù)內(nèi)幕:深入解析Spark內(nèi)核架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)原理
- HTML并不簡(jiǎn)單:Web前端開(kāi)發(fā)精進(jìn)秘籍
- Spring Web Services 2 Cookbook
- HTML5 Canvas核心技術(shù):圖形、動(dòng)畫(huà)與游戲開(kāi)發(fā)
- 深入大型數(shù)據(jù)集:并行與分布化Python代碼
- MySQL數(shù)據(jù)庫(kù)教程(視頻指導(dǎo)版)
- Scala編程(第4版)