Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could certainly construct a computing system that utilised either one of them as its only memory model. However, they both have rather different properties each with its own good and bad points. Most systems utilise both so as to get the benefits from each of them.</p> <p><strong>Stacks</strong></p> <p>A stack can be thought of as a pile of plates, you write a value on a plate and put it on the top of the stack this is called a push operation and stores a value on the stack. You can obviously also remove the top plate from the stack this is called a pop operation. But new allocations must always be at the top of the stack.</p> <p>The stack tend to be used for local variables and passing values between functions. Generally stacks have the following awesome properties:</p> <ul> <li>Requires only a handful of pointers to manage</li> <li>Very easy to implement in hardware, most processors have built in hardware support for a stack making it even faster.</li> <li>Very quick to allocate memory</li> </ul> <p>The problem with the stack comes from the fact items can only be added/removed from the top of the stack. Now this makes great sense when traversing up and down through function calls: pop functions inputs from the stack, allocate space for local variables on the stack, run function, clear local variables from the top of the stack and push the return value onto the stack. If on the other hand I want to allocate some memory and say pass it to another thread or in general free it far away from where it was allocated all of a sudden I have a problem, the stack is not in the correct position when I want to free the memory.</p> <p>You could say the stack facilitates fast sequential memory allocation.</p> <p><strong>Heap</strong></p> <p>Now the heap is different each allocation is generally tracked separately. This causes a lot of overhead for allocations and deallocations, but each one can be handled independently of other memory allocations, well until you run out of memory.</p> <p>There are numerous algorithms for accomplishing this and it is probably a bit unwise to twitter on about them here but here is a link that talks about a few good simple heap allocation algorithms: <a href="http://altdevblogaday.com/2011/02/12/alternatives-to-malloc-and-new/" rel="nofollow">Alternatives to malloc and new</a></p> <p>So the heap facilitates random memory allocation but this comes with a runtime penalty, however that penalty is often small that what would be incurred if you had to handle the situation using just the stack.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload