Intoduction to Stack¶
A stack is an abstract data type frequently used in computer science. It has a property that the Last item placed will be the first to be removed from it ( LIFO ) . Several options are defined on the stack , the most important ones are
push add an elemet to the top of the stack , and
pop removes elements from the top .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* The address of memory which is pointed by the Stack Pointer ( sp ) is the top of the stack */ ┌──────────────┐ <─ sp └──────────────┘ : push 0x10 /* sp is incremented and the value is stored at that address */ ┌──────────────┐ │ 0x10 │ └──────────────┘ <─ sp : push 0x20 ┌──────────────┐ │ 0x10 │ ├──────────────┤ │ 0x20 │ └──────────────┘ <─ sp : pop var /* The value pointed by the sp is removed from the stack and sp is decremented */ ┌──────────────┐ │ 0x10 │ └──────────────┘ <─ sp
Modern computers are designed with the need of high-level languages in mind. The most important technique for structuring programs introduced by high-level languages is the function. From one point of view, a function call alters the flow of control just as a jump does, but unlike a jump, when finished performing its task, a function returns control to the statement or instruction following the call. This high-level abstraction is implemented with the help of the stack.
The stack is also used to allocate local variables , to pass parameters to the functions, and to store the information needed to return to caller function after the execution of the function gets over.
The stack pointer is a special register which will allways point to the top of the stack , in x86-32 bit this register is called
esp .The area allocated on the stack for a function is called it's stack frame . and the registers
esp (in x86-32 bit system )are used to specify the boundaries of the stack frame . The
ebp will point to the staring of the stack frame of the current function and the
esp register will point to the bottom.