官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 沙湾县| 大连市| 鄄城县| 富顺县| 荆门市| 垦利县| 丰台区| 昌宁县| 花垣县| 河东区| 重庆市| 龙江县| 祁阳县| 井研县| 礼泉县| 忻州市| 炎陵县| 明溪县| 泰来县| 广宗县| 株洲市| 柘城县| 彰化市| 赤峰市| 沂源县| 张家界市| 皮山县| 垣曲县| 西吉县| 登封市| 惠安县| 九江县| 确山县| 井研县| 洪湖市| 博兴县| 光泽县| 梅河口市| 阜阳市| 静安区| 金坛市|