Open In App

Stack vs Heap Memory Allocation

Memory in a C/C++/Java program can either be allocated on a stack or a heap.
Prerequisite: Memory layout of C program.


Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack. And whenever the function call is over, the memory for the variables is de-allocated. This all happens using some predefined routines in the compiler. A programmer does not have to worry about memory allocation and de-allocation of stack variables. This kind of memory allocation is also known as Temporary memory allocation because as soon as the method finishes its execution all the data belonging to that method flushes out from the stack automatically. This means any value stored in the stack memory scheme is accessible as long as the method hasn't completed its execution and is currently in a running state.

Key Points:

int main()
{
  // All these variables get memory
  // allocated on stack
  int a;
  int b[10];
  int n = 20;
  int c[n];
}


 

Heap Allocation: The memory is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with the heap data structure. It is called a heap because it is a pile of memory space available to programmers to allocate and de-allocate. Every time when we made an object it always creates in Heap-space and the referencing information to these objects is always stored in Stack-memory. Heap memory allocation isn't as safe as Stack memory allocation because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program.

The Heap-memory allocation is further divided into three categories:- These three categories help us to prioritize the data(Objects) to be stored in the Heap-memory or in the Garbage collection.

Key Points:

int main()
{
   // This memory for 10 integers
   // is allocated on heap.
   int *ptr  = new int[10];
}

Intermixed example of both kinds of memory allocation Heap and Stack in java:

#include <iostream>
using namespace std;

int main()
{

    int a = 10; // stored in stack
    int* p = new int(); // allocate memory in heap
    *p = 10;
    delete (p);
    p = new int[4]; // array in heap allocation
    delete[] p;
    p = NULL; // free heap
    return 0;
}
class Emp {
    int id;
    String emp_name;

    public Emp(int id, String emp_name) {
        this.id = id;
        this.emp_name = emp_name;
    }
}

public class Emp_detail {
    private static Emp Emp_detail(int id, String emp_name) {
        return new Emp(id, emp_name);
    }

    public static void main(String[] args) {
        int id = 21;
        String name = "Maddy";
        Emp person_ = null;
        person_ = Emp_detail(id, name);
    }
}
// Define the Emp class with id and emp_name properties
class Emp {
    constructor(id, emp_name) {
        this.id = id; // Initialize id
        this.emp_name = emp_name; // Initialize emp_name
    }
}

// Create an instance of the Emp class
const person = new Emp(21, "Maddy"); // Initialize person with id 21 and emp_name "Maddy"
console.log(person); // Output the person object to the console

Following are the conclusions on which we'll make after analyzing the above example:

Pictorial representation as shown in Figure.1 below:

Fig.1

Key Differences Between Stack and Heap Allocations 
 

  1. In a stack, the allocation and de-allocation are automatically done by the compiler whereas, in heap, it needs to be done by the programmer manually.
  2. Handling the Heap frame is costlier than handling the stack frame.
  3. Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation.
  4. Stack frame access is easier than the heap frame as the stack has a small region of memory and is cache-friendly but in the case of heap frames which are dispersed throughout the memory so it causes more cache misses.
  5. A stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered.
  6. Accessing the time of heap takes is more than a stack.

Comparison Chart

ParameterSTACKHEAP
BasicMemory is allocated in a contiguous block.Memory is allocated in any random order.
Allocation and De-allocationAutomatic by compiler instructions.Manual by the programmer.
CostLessMore
ImplementationEasyHard
Access timeFasterSlower
Main IssueShortage of memoryMemory fragmentation
Locality of referenceExcellentAdequate
SafetyThread safe, data stored can only be accessed by the ownerNot Thread safe, data stored visible to all threads
FlexibilityFixed-sizeResizing is possible
Data type structureLinearHierarchical
PreferredStatic memory allocation is preferred in an array.Heap memory allocation is preferred in the linked list.
SizeSmall than heap memory.Larger than stack memory.
Article Tags :