Peter Lake
Peter Lake

Reputation: 61

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?

Upvotes: 1

Views: 497

Answers (2)

user1548400
user1548400

Reputation: 11

  • Stack can save space
    • We use heap primarily when we wish to control the object's lifetime ,allocating temporary buffer on heap memory which is not used after the end of a function(say) wastes heap memory that can be reused.

  • Stack can be faster than heap
    • The process of memory allocation in stack is constant (a couple of machine instructions inserted by your compiler during linking) and quick . Memory allocation on heap is slower (function call to glibc and a search routine) especially if it is fragmented .

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

StilesCrisis
StilesCrisis

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

Related Questions