Reputation: 61
From what I've learned about dynamic memory allocation, the heap seems just to be an abundant pool of memory that you can use as much as you want of. My question is, why don't you just always use the heap for variables and objects, and forget about the stack?
Upvotes: 1
Views: 497
Reputation: 11
I would prefer a stack when I need considerable memory for performing a single calculation and the project involves performing many such calculations. I would not fragment the memory using heap.
It is fine to use stack as long as one doesnt exceed a few hundred bytes ,anything more might try to overwrite other segments of your process crashing it with an exception.
Upvotes: 1
Reputation: 16290
Allocation on the stack is "free" from a performance perspective. Heap allocation is relatively expensive.
Also, conceptually, it makes it easy for objects to be discarded immediately after going out of scope.
Upvotes: 4