Memory Management (Basics)

Process

Each process is running on its own virtual address space. The MMU does the necessary translation from/to the physical address space. Every thread within a process has its own stack.

High address |-------------------|
             | Command Line Args |
             |-------------------|
             | Stack (Thread 0)  |
             |-------------------|
             |         ↓         |
             |-------------------|
             | Stack (Thread N)  |
             |-------------------|
             |         ↓         |
             |                   |
             |         ↑         |
             |-------------------|
             |       Heap        |
             |-------------------|
             |       Data        |
             |-------------------|
             |       Code        |
Low address  |-------------------|
                    Process

The value of the high address depends on the CPU (32-bit: 0x7FFFFFFF, 64-bit: 0x7FFFFFFFFFF).


Stack

With every function call a new stack frame gets created for the callee on the stack and as soon as it returns to the caller function that stack frame has been destructed.

                                      /|----------------------|
                                     / | Caller-saved Reg [1] |
                                    /  |----------------------|
                                   /   |     Parameter 1      |
High address |---------------|    /    |----------------------|
             | Stack Frame 0 |   /     |     Parameter 0      |
             |---------------|  /      |----------------------|
             | Stack Frame 1 | /       |   Caller Ret Addr    | (Old IP / LR [3])
             |---------------|/        |----------------------|
             | Stack Frame 2 |         |   Caller Frame Ptr   | (Old BP / FP)
Low address  |---------------|\        |----------------------| <-- Frame Pointer
                  Stack        \       | Callee-saved Reg [2] |
                                \      |----------------------|
                                 \     |     Local Var 0      |
                                  \    |----------------------|
                                   \   |     Local Var 1      |
                                    \  |----------------------|
                                     \ |     Temp Objects     |
                                      \|----------------------| <-- Stack Pointer
                                            Stack Frame 2

[1] Cached by the caller if it wants the old state later on. (for x86: EAX, ECX, EDX)
[2] Cached by the callee if it wants to use them by their own. (for x86: EBX, ESI, EDI)
[3] In the stack frame of a leaf function the LR won't be stored on the stack.


Heap

The data on the heap isn't as moderated and strictly structured as the one on the stack. You even have to clean up by yourself, if you haven't got a garbage collector.