@rkenmi - Stack Memory vs. Heap Memory

Stack Memory vs. Heap Memory


Stack Memory vs. Heap Memory


Back to Top

Updated on January 1, 2023

Stack Memory

The stack memory is used within a context of a thread. It is called stack memory since memory blocks are allocated in LIFO order, based on the function call stack. Each stack memory block houses data for local variables, references, and other bookkeeping data.

  • Faster, since each byte in the stack is used very frequently, it tends to use the CPU cache
  • Fixed in size
    • It is specifically the range of memory that is accessible via the Stack register of the CPU
  • No control for allocation and de-allocation of memory
  • Includes function calls and variables for function arguments, primitive values (int, char, etc.)
  • Includes references (a.k.a pointers)
  • Memory is allocated in contiguous blocks = faster lookup
  • Can result in the dreaded stack overflow

Heap Memory

The heap memory is used within the context of an application, which may use one or more threads. The heap memory allows you to use a much wider range of available system memory in a dynamic fashion. Languages like C/C++ and Java can utilize heap memory by instantiating objects using the new keyword. Depending on the language, they can also grant direct controls to manipulating objects in heap memory, i.e. malloc().

  • Performance is slower than stack memory
    • Global management of allocation/de-allocation of memory is more complex
    • Concurrency management across all threads, e.g. synchronization and locking control. Heap memory is used from an application context, rather than by thread context.
  • Usable memory is dynamic in size and in general, much larger than the stack
    • Allocated memory can be resized at runtime
  • Control for allocation and de-allocation of memory
    • malloc and calloc are examples of manually allocating memory in the heap in C/C++.
  • Includes objects that references (or pointers) point to
  • Includes arrays
  • Memory is allocated in non-contiguous blocks, so cache misses are frequent.
  • Can result in heap overflow

Article Tags:
Computer Sciencememory addressmemorystackheap