stack
Stack
The stack space is located just under the OS kernel space, generally opposite the heap area and grows downwards to lower addresses.
The stack is LIFO ( last-in-first-out ) data structure. In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations:
push
, which adds an element to the collection, andpop
, which removes the most recently added element that was not yet removed.
This area is devoted to storing all the data needed by a function call in a program. Calling a function is the same as pushing the called function execution onto the top of the stack, and once that function completes, the results are returned popping the function off the stack. The dataset pushed for function call is named a stack frame, and it contains the following data:
- the arguments (parameter values) passed to the routine
- the return address back to the routine’s caller space for the local variables of the routine
int main() {
int result = getResult();
}
int getResult() {
int num1 = getNum1();
int num2 = getNum2();
return num1 + num2;
}
int getNum1() {
return 10;
}
int getNum2() {
return 20;
}
Registers
-
esp
- register containing the address at the top of the stack. -
ebp
- register containing the address at the bottom of the stack frame. -
eip
- register containing the address of instruction to be executed.
Instructions
mov dest, src
: copy 4 bytes from src to dest.
For registers, move their value, and for
addresses, move the data at the address.
(Intel notation)
jmp address
: execute the instruction at
address
pop reg
= mov reg, ESP; add ESP, 4
``push data= sub ESP, 4; mov data, ESP
enter N bytes= push EBP; mov EBP, ESP; sub ESP, N bytes (required for locals)
call func=
push EIP; jmp func address
leave=
mov ESP, EBP; pop EBP
ret=
pop EIP; jmp EIP`
Heap
The Heap is the segment where dynamic memory allocation usually takes place.
The allocation to the heap area occurs, in the following cases.
- memory size is dynamically allocated at run-time
- scope is not limited. (i.g., variables referenced from several places)
- memory size is very large.
It’s our responsibility to free memory on the heap. The objects on the heap lead to memory leaks if they are not freed. In garbage-collected languages, the garbage collector frees memory on the heap and prevents memory leaks.
Data
The data segment contains initialized global and static variables which have a pre-defined value and can be modified. it’s divided into a read-only and a read-write space.