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

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.

Leave a Comment