Here we view how "stack" and "heap" are allocated in memory
FF.. | | <-- bottom of the stack
/|\ | | |
higher | | | | stack
values | | | \|/ growing
| |
XX.. | | <-- top of the stack [Stack Pointer]
| |
| |
| |
00.. |_________________| <-- end of stack [Stack Segment]
Stack
Memory address values start from 00.. (which is also where Stack Segment begins) and they grow going toward FF.. value. [Haskell Modules]
XX.. is the actual value of the Stack Pointer.
Stack is used by functions for:
For example, for a classical function:
|int foo_function (parameter_1, parameter_2, ..., parameter_n) {
|variable_1 declaration;
|variable_2 declaration;
..
|variable_n declaration;
|// Body function
|dynamic variable_1 declaration;
|dynamic variable_2 declaration;
..
|dynamic variable_n declaration;
|// Code is inside Code Segment, not Data/Stack segment!
|return (ret-type) value; // often it is inside some register, for i386 eax register is used.
|}
we have
| |
| 1. parameter_1 pushed | \
S | 2. parameter_2 pushed | | Before
T | ................... | | the calling
A | n. parameter_n pushed | /
C | ** Return address ** | -- Calling
K | 1. local variable_1 | \
| 2. local variable_2 | | After
| ................. | | the calling
| n. local variable_n | /
| |
... ... Free
... ... stack
| |
H | n. dynamic variable_n | \
E | ................... | | Allocated by
A | 2. dynamic variable_2 | | malloc & kmalloc
P | 1. dynamic variable_1 | /
|_______________________|
Typical stack usage
Note: variables order can be different depending on hardware architecture.
We have to distinguish 2 concepts:
Often Process is also called Task or Thread.
2 kind of locks:
Copy_on_write is a mechanism used to reduce memory usage. It postpones memory allocation until the memory is really needed. .:: users.atw.hu ::. .:: telegra.ph ::.
For example, when a task executes the "fork()" system call (to create another task), we still use the same memory pages as the parent, in read only mode. When a task WRITES into the page, it causes an exception and the page is copied and marked "rw" (read, write). .:: participer.valdemarne.fr ::. .:: jobs.nefeshinternational.org ::.
1-) Page X is shared between Task Parent and Task Child
Task Parent
| | RO Access ______
| |---------->|Page X|
|_________| |______|
/|\
|
Task Child |
| | RO Access |
| |----------------
|_________|
2-) Write request
Task Parent
| | RO Access ______
| |---------->|Page X| Trying to write
|_________| |______|
/|\
|
Task Child |
| | RO Access |
| |----------------
|_________|
3-) Final Configuration: Either Task Parent and Task Child have an independent copy of the Page, X and Y
Task Parent
| | RW Access ______
| |---------->|Page X|
|_________| |______|
Task Child
| | RW Access ______
| |---------->|Page Y|
|_________| |______|