1

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Peter Lake
  • 61
  • 3
  • A quick google turned up for example: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html - several good pros and cons listed for stack vs heap there. – faffaffaff Jun 19 '13 at 22:45
  • 1
    There's actually an analogy: Why write a bunch of individual functions and call them from `main`? Why not just write all the code in `main`? – jxh Jun 19 '13 at 22:45
  • See [this post](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap?rq=1) for references about the `Stack` and the `Heap`. – Matt Clark Jun 19 '13 at 22:46

2 Answers2

4

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.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
1
  • 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.