Why would you ever want to allocate memory on the heap rather than the stack?

Matthew picture Matthew · Oct 11, 2009 · Viewed 15.4k times · Source

Possible Duplicate:
When is it best to use a Stack instead of a Heap and vice versa?

I've read a few of the other questions regarding the heap vs stack, but they seem to focus more on what the heap/stack do rather than why you would use them.

It seems to me that stack allocation would almost always be preferred since it is quicker (just moving the stack pointer vs looking for free space in the heap), and you don't have to manually free allocated memory when you're done using it. The only reason I can see for using heap allocation is if you wanted to create an object in a function and then use it outside that functions scope, since stack allocated memory is automatically unallocated after returning from the function.

Are there other reasons for using heap allocation instead of stack allocation that I am not aware of?

Answer

caf picture caf · Oct 11, 2009

There are a few reasons:

  • The main one is that with heap allocation, you have the most flexible control over the object's lifetime (from malloc/calloc to free);
  • Stack space is typically a more limited resource than heap space, at least in default configurations;
  • A failure to allocate heap space can be handled gracefully, whereas running out of stack space is often unrecoverable.

Without the flexible object lifetime, useful data structures such as binary trees and linked lists would be virtually impossible to write.