Thursday, April 20, 2006

heap vs. stack

http://c.ittoolbox.com/documents/popular-q-and-a/stack-vs-heap-2112

Traditionally in a process address space you would see stack growing upside down and heap growing upwards. An application wise difference is all the memory allocated dynamically gets allocated on heap viz. malloc free, calloc etc. The stack of an process contains stack frames( containing the return address linkage for a function and the data required in a stack which has the qualifier 'auto').

Efficiency-wise, one thing I can think of is memory on stack should be a bit faster to access as the hit-ratio for the pages having stack memory should have a better chances in terms of cache and also virtual memory. There should be a few more here, which can be same as choice of using array vs new().

The stack is basically a queue which gets (over-)written a lot. It is really intended for function parameters and return codes. Better yet, I would even suggest not having any parameters in functions which are big (for instance a struct or a class).

ALSO: http://www.cnds.jhu.edu/courses/cs111/lect3_600.111/text4.htm

Heap vs. Stack

  • Stack:

    • Grows ‘down’
    • Operations always happen at the top: push and pop, organized
    • It provides support for recursive functions
  • Heap:

    • Grows ‘up’
    • The order in which objects are created/destroyed is totally under the control of the programmer.
    • It is not organized, you can have holes.