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
- Memory is allocated in **contiguous blocks within the **call stack.
- The size of memory required is **already known before execution.
- When a **function is called, its **local variables are allocated on the stack.
- Once the function **finishes execution, the allocated memory is **automatically freed.
- The programmer **does not need to handle allocation or deallocation.
- Since stack memory is freed when a function completes, it is also called **temporary memory allocation.
Key Features of Stack Allocation
- Memory is available **only while the function is running.
- **Automatic deallocation occurs when the function ends.
- If the **stack memory is full, an error like **Java.lang.StackOverflowError occurs in Java and segmentation fault in C++.
- **Safer than heap memory, as data can only be accessed by the **owner thread.
- **Faster than heap allocation due to automatic memory management.
**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:
- **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.
- **Old (Tenured) Generation – Holds **older objects that are no longer frequently used. These objects stay in memory unless explicitly removed.
- **Permanent Generation (PermGen) – Stores **JVM metadata, such as **runtime classes and **application methods.
Key Features of Heap Allocation
- If heap memory is **full, JVM throws an error: **java.lang.OutOfMemoryError.
- Unlike stack memory, **automatic deallocation does not happen; a **garbage collector is needed to free unused memory.
- **Slower than stack memory due to **manual allocation and garbage collection.
- **Less thread-safe, as heap memory is **shared among all threads.
- **Typically larger in size compared to stack memory.
- Heap memory **persists as long as the **entire application is running.
**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:
- **Heap Memory Allocation:
- When the program starts, all runtime classes are stored in heap memory.
- **Stack Memory Allocation:
- The main method is stored in stack memory along with its local variables and reference variables.
- The reference variable Emp of type Emp_detail is stored in the stack and points to the corresponding object in heap memory.
- **Constructor Call and Memory Allocation:
- The parameterized constructor Emp(int, string) is invoked from main, and its execution is allocated at the top of the stack.
- Inside the constructor: The object reference is stored in stack memory, the primitive integer id is stored in stack memory and the string reference emp_name is stored in stack memory, but it points to the actual string stored in the string pool (heap memory).
- **Function Call and Memory Allocation:
- When Emp_detail() is called from main, a new stack frame is created on top of the previous stack frame.
- The newly created Emp object and all its instance variables are stored in heap memory.
**Pictorial representation as shown in the diagram below:

**Key Differences Between Stack and Heap Allocations
- 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.
- Handling the Heap frame is **costlier than handling the stack frame.
- **Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is **fragmentation.
- 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.
- A stack is **not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be **altered.
- **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. |