Memory Allocation
1. Three Strategies
Compiler assigns storage for every name: static (fixed), stack (LIFO frames), heap (dynamic). Choice depends on lifetime + size known-ness.
2. Comparison
| Static | Stack | Heap | |
|---|---|---|---|
| When decided | compile time | call time | run time (malloc/new) |
| Size known? | yes, fixed | frame size fixed, depth varies | varies |
| Recursion? | No | Yes | Yes (via pointers) |
| Dealloc | never (whole run) | auto on return | manual / GC |
| Holds | globals, constants | locals, params, temps | objects, closures, variable arrays |
3. Offset Assignment (static/stack)
offset = 0
for each local in order: addr = fp + offset; offset += width(type)
// aligns to 4/8 bytes; temps appended after locals
Example int a; float b[10]; in frame: a at +0 (4B), b at +4 (40B), next temp at +44.
4. Heap Management
malloc carves from free list; free returns; fragmentation handled by coalescing; GC (mark-sweep) reclaims unreachable in Java/Python.
5. Exam Points
- Compare static vs stack vs heap — 7 marks, very frequent.
- Offset computation for decls — 5 marks, frequent.
- Fragmentation / GC basics — 3 marks, frequent.