Can refer to either the heap data structure or heap memory. See Heap (data structure) for the data structure.
A distinct area of RAM used for data storage. Other area is the Stack.
The heap is a large pool of memory used for dynamic allocation.
- Management: Managed by the programmer (e.g.,
malloc/freein C) or a Garbage Collector (e.g., in Python or Java). - Data Stored: Large objects, global variables, and data structures where the size is unknown at compile time.
- Allocation: Non-contiguous. Finding a free block leads to fragmentation over time.
- Size: Dynamic and limited only by physical RAM or virtual memory.
- Lifetime: Persists until manually freed or garbage collected.
| Feature | Stack | Heap |
|---|---|---|
| Speed | Very Fast | Slower (overhead for searching blocks) |
| Access | Sequential | Random (via pointers) |
| Safety | High (automatic cleanup) | Low (potential for memory leaks/pointers) |
| Structure | Linear/Ordered | Hierarchical/Unordered |