Memory Management Basics
Stack vs heap, allocation, garbage collection, leaks.
memorybasicsUpdated 2025-09-01
Stack vs Heap
- Stack: automatic, function frames, fast.
- Heap: dynamic allocation (new / malloc), manual or GC.
Lifecycle
- Allocate → Use → Release (manual) or GC sweeps unreachable objects.
Problems
- Leaks: lost reference to allocated block.
- Dangling pointer: freed memory still referenced.
- Fragmentation: many small gaps.
Example (Java)
- int x = 10; // stack primitive
- int[] a = new int[3]; // heap array