Dynamic Memory Allocation
intermediateDynamic memory allocation creates variables at runtime (on the heap).
Why Dynamic Memory?
- Size determined at runtime
- Lifetime extends beyond scope
- Essential for data structures (linked lists, trees)
new and delete
new[] and delete[]
Heap vs Stack
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Manual (new/delete) |
| Speed | Fast | Slower (system calls) |
| Size | Small (1-8 MB) | Large (limited by RAM) |
| Lifetime | Scope-based | Manual |
Memory Leaks
Fix:
When to Use Dynamic Memory
- Array size unknown at compile time
- Data that must persist beyond scope
- Large data that would overflow the stack
Common mistakes: pairing new with delete or new[] with delete (mismatched forms are undefined behavior), and losing the only pointer to a block before deleting it, which leaks it.
Key takeaway: Dynamic allocation (new/delete) manages heap memory — always pair new with delete to avoid leaks.
Try it: Allocate a single int with new, set it to 42, print it, then delete it and set the pointer to nullptr.