Skip to content

Stack vs heap

MarJC5 edited this page Nov 8, 2022 · 1 revision

Stack Allocation:

  • It’s a temporary memory allocation scheme where the data members are accessible only if the method( ) that contained them is currently is running.
  • It allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution.
  • Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread.
  • Memory allocation and de-allocation is faster as compared to Heap-memory allocation.
  • Stack-memory has less storage space as compared to Heap-memory.
int main()
{
    // All these variables get memory
    // allocated on stack
    int a;
    int b[10];
    int n = 20;
    int c[n];
}

Heap Allocation:

  • This memory allocation scheme is different from the Stack-space allocation, here no automatic de-allocation feature is provided. We need to use a Garbage collector to remove the old unused objects in order to use the memory efficiently.
  • The processing time(Accessing time) of this memory is quite slow as compared to Stack-memory.
  • Heap-memory is also not threaded-safe as Stack-memory because data stored in Heap-memory are visible to all threads.
  • Size of Heap-memory is quite larger as compared to the Stack-memory.
  • Heap-memory is accessible or exists as long as the whole application runs.
int main()
{
   // This memory for 10 integers
   // is allocated on heap.
   int *ptr  = new int[10];
}
Parameter STACK HEAP
Basic Memory is allocated in a contiguous block. Memory is allocated in any random order.
Allocation and De-allocation Automatic by compiler instructions. Manual by the programmer.
Cost Less More
Implementation Easy Hard
Access time Faster Slower
Main Issue Shortage of memory Memory fragmentation
Locality of reference Excellent Adequate
Safety Thread safe, data stored can only be accessed by owner Not Thread safe, data stored visible to all threads
Flexibility Fixed-size Resizing is possible
Data type structure Linear Hierarchical
Preferred Static memory allocation is preferred in array. Heap memory allocation is preferred in the linked list.
Size Small than heap memory. Larger than stack memory.
Clone this wiki locally