Variables created on the stack will go out of scope and
Much faster to allocate in comparison to variables on the
Implemented with an actual stack data structure.
Stores local data, return addresses, used for parameter
Can have a stack overflow when too much of the stack is
used. (mostly from inifinite (or too much) recursion, very large
Data created on the stack can be used without
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
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
Used on demand to allocate a block of data for use by the
Can have fragmentation when there are a lot of allocations
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
char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
bool b = true; // Allocated on the stack.
//Create 500 bytes on the stack
//Create 500 bytes on the heap
pBuffer = new char;
}//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete pBuffer;