0
When should I use the dynamic memory for a variable?
i dont understand the use of the heap and the stack.
1 Answer
+ 3
The stack concerns memory allocated to the program when it's first run. You've got a limited amount of stack memory to work with (this is why you can run into "stack overflow" errors; the maximum size of the stack depends on the operating environment). As opposed to dynamic memory, memory allocated on the stack is referred to as static memory.
The stack grows "up"-- When you allocate new memory, it's pushed on top of the stack, and popped back off when it's no longer in use. You can consider it like a stack of plates. When you put a plate on top, that's the first one you take off (you don't want to be pulling plates out of the middle).
You use the heap when you need to allocate memory at run-time. One of the biggest differences compared to the stack is that heap memory is non-contiguous. You can have one object stored in one place, and then another one a thousand memory addresses away.
Now putting all of this together, you can see the problem: We can only "free" memory on the stack by removing the last thing we put onto it. Using the heap, we can allocate and free memory wherever and however we want.
tl;dr: If you don't know how much memory you're going to need at compile time, you'll need to allocate that memory on the heap.