Dynamic storage allocation is based on run time. We say that a storage allocation decision is dynamic if it can be decided only while the program is running. The following two strategies are based on dynamic storage allocation:
- Stack Storage Allocation.
- Heap Storage Allocation.
Stack Storage Allocation:
- Stored in computer RAM like the heap.
- Variables created on the stack will go out of scope and automatically deallocate.
- Much faster to allocate in comparison to variables on the heap. Implemented with an actual stack data structure.
- Stores local data, return addresses, used for parameter passing Can have a stack overflow when too much of the stack is used. (mostly from infinite (or too much) recursion, very large allocations)
- Data created on the stack can be used without pointers.
- You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
- Usually has a maximum size already determined when your program starts.
Heap Storage Allocation:
- Stored in computer RAM like the stack.
- Variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[ ] or free
- Slower to allocate in comparison to variables on the stack.
- Used on demand to allocate a block of data for use by the program.
- Can have fragmentation when there are a lot of allocations and deallocations
- In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc
- Can have allocation failures if too big of a buffer is requested to be allocated.
- You would use the heap if you don’t know exactly how much data you will need at runtime or if you need to allocate a lot of data. Responsible for memory leaks