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

15,981

Solution 1

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.

Solution 2

  1. You want an allocation to live beyond a function invocation
  2. You want to conserve stack space (which is typically limited to a few MBs)
  3. You're working with re-locatable memory (Win16, databases, etc.), or want to recover from allocation failures.
  4. Variable length anything. You can fake around this, but your code will be really nasty.

The big one is #1. As soon as you get into any sort of concurrency or IPC #1 is everywhere. Even most non-trivial single threaded applications are tricky to devise without some heap allocation. That'd practically be faking a functional language in C/C++.

Solution 3

So I want to make a string. I can make it on the heap or on the stack. Let's try both:

char *heap = malloc(14);
if(heap == NULL)
  {
    // bad things happened!
  }
strcat(heap, "Hello, world!");

And for the stack:

char stack[] = "Hello, world!";

So now I have these two strings in their respective places. Later, I want to make them longer:

char *tmp = realloc(heap, 20);
if(tmp == NULL)
  {
    // bad things happened!
  }
heap = tmp;
memmove(heap + 13, heap + 7);
memcpy(heap + 7, "cruel ", 6);

And for the stack:

// umm... What?

This is only one benefit, and others have mentioned other benefits, but this is a rather nice one. With the heap, we can at least try to make our allocated space larger. With the stack, we're stuck with what we have. If we want room to grow, we have to declare it all up front, and we all know how it stinks to see this:

char username[MAX_BUF_SIZE];

Solution 4

The most obvious rationale for using the heap is when you call a function and need something of unknown length returned. Sometimes the caller may pass a memory block and size to the function, but at other times this is just impractical, especially if the returned stuff is complex (e.g. a collection of different objects with pointers flying around, etc.).

Solution 5

Size limits are a huge dealbreaker in a lot of cases. The stack is usually measured in the low megabytes or even kilobytes (that's for everything on the stack), whereas all modern PCs allow you a few gigabytes of heap. So if you're going to be using a large amount of data, you absolutely need the heap.

Share:
15,981

Related videos on Youtube

Matthew
Author by

Matthew

Updated on June 30, 2021

Comments

  • Matthew
    Matthew almost 3 years

    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?

    • Kiran Kumar
      Kiran Kumar over 14 years
    • Jonathan Leffler
      Jonathan Leffler over 14 years
      @Naveen: Sorta - the other is a C++ question where this is C, so some of the answers discuss 'delete' and 'new' which are not applicable to C.
  • visual_learner
    visual_learner over 14 years
    Once again I must make the "function x() is a non-standard function" comment. alloca() is found on many platforms in some form or another, but is not a part of any standard.
  • caf
    caf over 14 years
    Chris: This is absolutely true, however in the context of a wider discussion of heap versus stack allocation, the existence of alloca() in some places is useful to consider. Particularly because it shows neatly that the limitation on runtime calculation of the allocation size is a restriction imposed by C, not something inherent to the idea of stack-based allocation.
  • onepiece
    onepiece over 4 years
    Stack space is typically a more limited resource than heap space - why?
  • caf
    caf over 4 years
    @onepiece: It mostly comes down to default process layout choices and stack limits, but there is also the underlying fact that each thread in a process needs a single contiguous block of virtual memory carved out for its stack.