Search code examples
memorydynamicheap-memoryallocationstack-memory

Why use the stack? Why not just heap? - C/C++


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?


Solution

  • 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.