Open In App

Stack vs Heap Memory Allocation

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  • It’s a temporary memory allocation scheme where the data members are accessible only if the method( ) that contained them is currently running.
  • It allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution.
  • We receive the corresponding error Java. lang. StackOverFlowError by JVM, If the stack memory is filled completely.
  • Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be accessed by the owner thread.
  • Memory allocation and de-allocation are faster as compared to Heap-memory allocation.
  • Stack memory has less storage space as compared to Heap-memory.
C++
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.

  • Young Generation – It’s the portion of the memory where all the new data(objects) are made to allocate the space and whenever this memory is completely filled then the rest of the data is stored in Garbage collection.
  • Old or Tenured Generation – This is the part of Heap-memory that contains the older data objects that are not in frequent use or not in use at all are placed.
  • Permanent Generation – This is the portion of Heap-memory that contains the JVM’s metadata for the runtime classes and application methods.

Key Points:

  • We receive the corresponding error message if Heap-space is entirely full,  java. lang.OutOfMemoryError by JVM.
  • 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 as threaded-safe as Stack-memory because data stored in Heap-memory are visible to all threads.
  • The size of the Heap-memory is quite larger as compared to the Stack-memory.
  • Heap memory is accessible or exists as long as the whole application(or java program) runs.
CPP
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:

C++
#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;
}
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
def main():
    a = 10  # stored in stack
    p = None  # declaring p variable
    p = 10  # allocating memory in heap
    del p  # deleting memory allocation in heap
    p = [None] * 4  # array in heap allocation
    p = None  # free heap
    return 0


if __name__ == "__main__":
    main()
JavaScript
// 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:

  • As we start execution of the have program, all the run-time classes are stored in the Heap-memory space.
  • Then we find the main() method in the next line which is stored in the stack along with all its primitive(or local) and the reference variable Emp of type Emp_detail will also be stored in the Stack and will point out to the corresponding object stored in Heap memory.
  • Then the next line will call to the parameterized constructor Emp(int, String) from main( ) and it’ll also allocate to the top of the same stack memory block. This will store:
    • The object reference of the invoked object of the stack memory.
    • The primitive value(primitive data type) int id in the stack memory.
    • The reference variable of the String emp_name argument will point to the actual string from the string pool into the heap memory.
  • Then the main method will again call to the Emp_detail() static method, for which allocation will be made in stack memory block on top of the previous memory block.
  • So, for the newly created object Emp of type Emp_detail and all instance variables will be stored in heap memory.

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.
SizeSmaller than heap memory.Larger than stack memory.


Previous Article
Next Article

Similar Reads

Difference Between Static Allocation and Heap Allocation
In programming, there are two approaches to memory management and these are static allocation and heap allocation. In static allocation, memory is determined at the compile time, where the size and position of each data structure for example arrays, variable are constant throughout the program. While this approach may help to give faster access, it
5 min read
Difference between Static allocation and Stack allocation
Static Allocation: Static allocation is a procedure which is used for allocation of all the data objects at compile time. Static allocation is possible only when the compiler knows the size of data object at compile time. In this type of allocation, formation of data objects is not possible under any circumstances at run time. In static allocation,
2 min read
Why Linked List is implemented on Heap memory rather than Stack memory?
Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind
14 min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Difference Between Contiguous and Non-Contiguous Memory Allocation
Memory management is one of the fundamentals of operating systems that has implications for its performances and use of resources. These are discussed below: Contiguous and non-contiguous allocation of memory Allocation of memory may take either of the following forms: This article enables you to know the difference between the two, how memory is a
5 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property states that it should be A Complete Binary Tree. For
4 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Memory representation of Binomial Heap
Prerequisites: Binomial Heap Binomial trees are multi-way trees typically stored in the left-child, right-sibling representation, and each node stores its degree. Binomial heaps are collection of binomial trees stored in ascending order of size. The root list in the heap is a linked list of roots of the Binomial heap. The degree of the nodes of the
2 min read
What is a Memory Heap?
What is Heap memory? Heaps are memory areas allocated to each program. Memory allocated to heaps can be dynamically allocated, unlike memory allocated to stacks. As a result, the heap segment can be requested and released whenever the program needs it. This memory is also global, which means that it can be accessed and modified from wherever in the
5 min read
Heap overflow and Stack overflow
Heap Overflow: Heap is a region of process's memory which is used to store dynamic variables. These variables are allocated using malloc() and calloc() functions and resize using realloc() function, which are inbuilt functions of C. These variables can be accessed globally and once we allocate memory on heap it is our responsibility to free that me
3 min read
Stack Vs Heap Data Structure
What is Stack? A stack is a linear data structure where the last element entered exits first. The order of stack data structure might be LIFO, FILO: According to this technique, the piece that is in last will come out first. As an example, consider a stack of dishes stacked on top of each other. The plate we put last is on top, and because we take
3 min read
How to implement stack using priority queue or heap?
How to Implement stack using a priority queue(using min heap)? Asked In: Microsoft, Adobe.  Solution: In the priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in the Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a k
6 min read
Difference Between Eidetic Memory and Photographic Memory
Difference Between Eidetic Memory and Photographic Memory: Eidetic memory and photographic memory are two distinct forms of human memory. Memory is the capacity to gather, retain, and recall information. This cognitive function hinges on three primary processes: encoding, storage, and retrieval. Human memory encompasses the capacity to maintain and
10 min read
Difference between Volatile Memory and Non-Volatile Memory
Memory is one of the most fundamental components in computing systems. Broadly, computer memory can be divided into two types namely volatile memory and non volatile memory. Even though both are crucial in the total functioning of the electronics, they are not interchangeable, each playing specific roles. Volatile memory deploys power in order to s
6 min read
Difference between Uniform Memory Access (UMA) and Non-uniform Memory Access (NUMA)
In computer architecture, and especially in Multiprocessors systems, memory access models play a critical role that determines performance, scalability, and generally, efficiency of the system. The two shared-memory models most frequently used are UMA and NUMA. This paper deals with these shared-memory models, explaining their characteristics, adva
5 min read
Difference between Virtual memory and Cache memory
Virtual Memory and Cache Memory are important substructures of contemporary computing systems that perform an important function in terms of enhancing capabilities. But they are dissimilar in terms of functionality and function differently. Virtual memory works as extra physical memory of the system and Cache memory provides quick access to frequen
5 min read
Difference between Random Access Memory (RAM) and Content Addressable Memory (CAM)
In the world of computation, memory plays a very significant role in ensuring efficient data processing and data storage or data retrieval. Memory system are the very crucial part of any particular digital devices , it facilitate to store and retrieve the Data from the devices . Two important types of memory are Random Access Memory ( RAM ) and Con
8 min read
How can the stack memory be increased?
A Stack is a temporary memory address space that is used to hold arguments and automatic variables during the invocation of a subprogram or function reference. The size of this stack is called the stack size. Stack ⤓⤒ Heap BSS DATA TEXT How to increase stack size? One cannot increase the stack size. The reason of this is as mentioned below: Reason:
2 min read
Is there a limit for the total variables size on the Memory Stack?
What is Stack?A stack is a conceptual structure made up of a collection of homogeneous elements that operates on the last in first out principle (LIFO). It is a popular abstract data type with two major operations: push and pop. Push and pop operations are performed on the topmost element, which is the most recently added item to the stack. The pus
2 min read
How to create an Array of Objects in the Stack memory?
What is an Array of Objects? An array of objects is a data structure that stores a collection of objects of the same type. The objects in the array are stored in contiguous memory locations, and the array provides indexed access to the objects. This means that you can access an individual object in the array using its index, just like you would wit
6 min read
Task Allocation to Game Slots
Given an array of n tasks, each represented by two arrays: start_time and duration. The start_time array represents the start time of each task, and the duration array represents the duration of each task. Your goal is to design an allocation strategy for these tasks to maximize their chances of being processed. The tasks need to be assigned to ava
10 min read
Post Box Allocation
Given with array of apartments where apartments[i] is the location of the ith apartment along a street and an integer p postboxes in the street. Return the minimum total distance between each apartment and its nearest postbox. Examples: Input : apartments = [ 1 , 4 , 8 , 10 , 20 ] , p = 3Output : 5Explanation : We allocate postboxes at location 3 ,
11 min read
CSES Solutions - Room Allocation
There is a large hotel, and N customers will arrive soon. Each customer wants to have a single room. You know each customer's arrival and departure day as timings[][] such that timings[i][0] is the arrival time and timings[i][1] is the departure time of ith person. Two customers can stay in the same room if the departure day of the first customer i
10 min read
Maximum Cinema Seat Allocation
A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum
8 min read
Minimizing Total Manhattan Distances for Driver-Package Allocation
Given two integers n and m, where n represents delivery drivers and m represents the number of packages, Additionally, their position are also given in drivers[][] and packages[][] respectively. The task is to allocate each driver a unique package such that the sum of total Manhattan distances between the drivers and their respective packages are m
14 min read
Difference between MEAN Stack and MEEN Stack
What are stacks? What is a stack, if you are familiar with full-stack development you might have come across the terms MEAN, MERN, MEVN, MEEN, etc. These are web stacks consisting of a collection of software and frameworks used for building a web application from the front-end and back-end. You can learn any of these stacks to become a Full-stack d
4 min read
three90RightbarBannerImg