Stack vs Heap Memory Allocation (original) (raw)

Last Updated : 26 Feb, 2025

In C, C++, and Java, memory can be allocated on either a **stack or a **heap. **Stack allocation happens in the **function call stack, where each function gets its own memory for variables. In C/C++, heap memory is controlled by programmer as there is no automatic garbage collection.

Stack Allocation

Stack allocation refers to the process of assigning memory for **local variables and **function calls in the **call stack. It happens **automatically when a function is called and is freed **immediately when the function ends. Since memory is managed by the system, it is **fast and efficient but has **limited space compared to heap allocation. If too many function calls exceed the stack's capacity, it results in a **stack overflow error.

How Stack Allocation Works

Key Features of Stack Allocation

**Example Code:

C++ `

int main() {

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

`

**Heap Allocation

Heap memory is allocated **dynamically during program execution. Unlike **stack memory, heap memory is **not freed automatically when a function ends. Instead, it requires **manual deallocation (In C/C++) or a **garbage collector (in Java or Python) to reclaim unused memory.

The name **heap has no relation to the **heap data structure; it simply refers to a large pool of memory available for **dynamic allocation. Whenever an **object is created, it is stored in **heap memory, while references to these objects are stored in **stack memory. Heap allocation is **less safe than stack allocation because heap data is **accessible by multiple threads, increasing the risk of **data corruption and **memory leaks if not handled properly.

**Categories of Heap Memory

Heap memory is divided into three categories, helping prioritize **object storage and **garbage collection:

  1. **Young Generation – Stores **new objects. When this space is full, unused objects are removed by the **garbage collector, and surviving objects move to the **Old Generation.
  2. **Old (Tenured) Generation – Holds **older objects that are no longer frequently used. These objects stay in memory unless explicitly removed.
  3. **Permanent Generation (PermGen) – Stores **JVM metadata, such as **runtime classes and **application methods.

Key Features of Heap Allocation

**Example Code:

CPP `

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

`

**To Understand the difference between **stack and heap memory allocation by observing how objects are created and managed in both cases using a class **Emp for storing Employee details

Below is the implementation:

C++ `

#include <bits/stdc++.h> using namespace std;

class Emp { public: int id; string emp_name;

// Constructor to initialize employee details
Emp(int id, string emp_name) {
    this->id = id;
    this->emp_name = emp_name;
}

};

// Function to create and return an Emp object Emp Emp_detail(int id, string emp_name) { return Emp(id, emp_name); }

int main() { // Initializing employee details int id = 21; string name = "Maddy";

// Creating an Emp object using the function
Emp person_ = Emp_detail(id, name);

return 0;

}

Java

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);
}

}

Python

class Emp: # Constructor to initialize employee details def init(self, id, emp_name): self.id = id self.emp_name = emp_name

Function to create and return an Emp object

def Emp_detail(id, emp_name): return Emp(id, emp_name)

if name == "main": # Initializing employee details id = 21 name = "Maddy"

# Creating an Emp object using the function
person_ = None
person_ = Emp_detail(id, name)

JavaScript

class Emp { // Constructor to initialize employee details constructor(id, emp_name) { this.id = id; this.emp_name = emp_name; } }

// Function to create and return an Emp object function Emp_detail(id, emp_name) { return new Emp(id, emp_name); }

// Initializing employee details let id = 21; let name = "Maddy";

// Creating an Emp object using the function let person_ = null; person_ = Emp_detail(id, name);

`

**Based on the above example, we can draw the following conclusions:

**Pictorial representation as shown in the diagram below:

**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 **time of heap takes is more than a stack.

**Comparison Chart

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 (in C or C++ and garbage collector in Java or Python)
Cost Less More
Implementation Easy Hard
Main Issue Shortage of memory Memory fragmentation
Locality of reference Excellent Adequate
Safety Thread safe, data stored can only be accessed by the 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 an array. Heap memory allocation is preferred in the linked list.
Size Smaller than heap memory. Larger than stack memory.