Stack vs Heap: Key Differences Between Stack And Heap

Go through this article to learn about the key differences between Stack vs Heap and the two different data structures for memory allocation:

Computer programs need a certain amount of memory to be allocated for execution. Memory allocation can either be dynamic or static.

In dynamic allocation, memory is allocated at the program run time. In static allocation, a fixed amount of memory is allocated at the compile time itself. When the program execution gets finished, this allocated memory is freed up.

In OOPs programming languages like C, C++, C#, Java, etc., the program can either be allocated to stack memory or heap memory. Stack and heap are two different data structures for memory allocation.

In this article, we aim to understand stack vs heap C++.

Stack vs Heap: A Comparison

Stack Vs Heap

Let us try to understand what is a stack and what is a heap, and what are the key differences between the two.

What is Stack

Stack is an abstract data type, a linear data structure that holds a collection of elements that are added or removed in a Last In First Out (LIFO) manner. This means the element added at the top will be removed first, just like we have a pile of plates one on top of the other and you will take out the plate at the top first.

Stack supports two main operations:

  1. Push: Adding a data item to the array or list.
  2. Pop: Removing the most recently added data item.

The size of the stack gets adjusted based on Push or Pop operation.

Suggested Reading => A Complete Study of Heap Sort With Examples

Stack-Based Memory Allocation

Stack memory gets allocated to adjacent blocks or chunks of memory. Since this allocation of memory happens in a function called stack, it is named as stack memory allocation.

Therefore, the popular use of stack at the architecture level is memory allocation. A stack is that part of a computer memory that is used for contiguous, temporary memory allocation. Stack has a fixed starting location, but variable size.

As mentioned above, this memory allocation is temporary in nature and stores local variables along with those arguments which are passed through a function along with their return addresses. All the data belonging to the function which completes execution is quickly removed from the stack.

What this really means is that the value stored in stack memory is available only until the execution is still running and it will automatically erase the stack memory after the task is completed.

Are you wondering what may happen in case a program consumes more memory than the size of the stack? Read further to get the answer.

Stack Overflow Error

As the name suggests, stack overflow is a situation in which a program draws more memory as compared to the size of the stack. This results in the failure of the program. In a situation when, for a recurring call, there is no specific base condition, as soon as the memory is filled up, a stack overflow error takes place.

One of the major shortcomings of the stack is that it is not possible to resize variables and memory allocation is done in one block. The size is limited depending on the OS in use and cannot be altered as they are fixed.

Important Features

Here are some important features of the stack:

  • Memory allocation is temporary and limits data accessibility to the point where the method that contains the data is still running.
  • Memory allocation and de-allocation are automatic at the completion of the execution of the corresponding method.
  • In case the stack memory is completely full, the error Java .lang. Stack OverFlow error occurs.
  • Stack memory allocation is comparatively safer than heap memory allocation, as the stored data is accessible only by the owner thread.
  • The process of memory allocation and deallocation is quicker when compared with the heap.
  • Heap storage has more storage size compared to stack.

Recommended Reading => Explore All about Stack Data Structure in C++


These include:

  • Stack memory offers multiple advantages to the programmer at the time of compilation of the code.
  • The process of allocation and deallocation of memory can be controlled.
  • The capability to manage data in LIFO (Last In First Out) gives the stack an edge over the heap.
  • Stack offers auto clean-up objects in memory and variables cannot be resized.
  • The local variables are stored in the “called function” in the stack and are quickly terminated on return.

But like every coin has another side, the stack has some disadvantages as well.


These have been discussed below:

  • Stack has a limited size for memory, which makes it unsuitable in case of the requirement of large memory size.
  • During the compilation of code, stack overflow can happen if the number of objects exceeds the size of the stack.

We have talked about stack memory and this discussion will be incomplete without looking at heap memory allocation.

Heap Memory Allocation

The allocation of heap memory takes place at the time of execution of the instructions of the programmer. The term heap refers to a collection of memory that can be allocated and deallocated by the programmer. Therefore, the heap has no relation to the heap data structure.

It is important to understand that while the construction of an object happens in a heap, however, the corresponding information for these objects is saved in stack memory. Heap memory often suffers from security issues due to the visibility and accessibility of data stored in all threads.

This, sometimes, can lead to a situation of memory leak in the application if the programmer misses handling heap memory with care.

In heap, data is stored in a hierarchical manner which leads to slow access as compared to stack. Do you remember how the old platter hard drives used to get clogged due to fragmentation? Something similar happens with heap memory as well. Fragmentation leads to the clogging of heap memory.

One of the major advantages of heap memory lies in the fact that there is no limitation on the size of the memory and it also allows for resizing of variables as and when needed.

Heap memory is stored randomly, and that explains the slow speed of access because the data will have to be pulled from multiple random places on the chip.


Here are some advantages of heap memory:

  • As mentioned above, the heap does not have any limitation on the size of memory. This feature gives the heap an added advantage over the stack.
  • The variables in heap memory can be accessed globally and can also be resized based on requirements.

So, are you wondering if the heap is the best choice? Hold on! It also has some disadvantages which are important to consider as they impact the speed and performance of the program.

Disadvantages of Heap

  • As compared to the stack, heap not only has a slower execution time but also the management of memory is a complicated process.
  • The computation process is also slow as compared to the stack. Continuous use of heap memory can consume all the RAM from the computer.

In case you are confused while making a choice between heap and stack, do not miss the next section of this article where we present a comparison between stack and heap.

While one point of similarity between heap and stack is that they are both stored on the RAM of the computer, there are many points difference between the two.

Heap vs Stack

The table below enumerates heap memory vs stack memory:

Point of comparisonStackHeap
Cost of usageLowHigh
Deallocation of variableNot necessaryClear deallocation is important
Access timeQuickSlow as compared to stack
Resizing requiredVariable size is fixedResizing of variable is possible.
DrawbacksLimited memoryFragmented memory due to allocation and later freeing up of memory
Allocation of memoryAutomaticManual
Order for allocation of memoryAllocated as a contiguous blockAllocated in a random order
Size of memoryLimited memory and dependent on OSUnlimited memory size

Stack vs Heap C++

Let us also take a quick look at stack vs heap in some programming languages like C++ and Java.

As mentioned earlier, the memory used by a program can be divided into separate segments.

Heap and stack are two segments we will discuss now in terms of the allocation of memory in C++ programming.

Stack vs Heap C++

The heap segment, which is also called the free store tracks memory and is used for dynamic allocation.

While programming in C++, whenever a new operator is used for the purpose of allocation of memory, it gets allocated in the heap segment. As soon as a variable that was dynamically allocated gets deleted, memory is sent back to the heap and is used again when more allocation requests are received.

In C, there are the below-mentioned functions are used for the purpose of allocation and deallocation of memory on the heap.

malloc ( )
calloc ( )
realloac ( )
free ( )

It is important to note that these functions will have to be used extremely carefully to avoid any memory leaks.

In C++, these are the functions namely:

new ( )
delete ( )

In order to use these functions, the user needs to specify the number of bytes that are to be allocated, and the address where the memory was allocated is returned. In this way, a programmer is able to operate with the given memory region based on requirements.

Heap is a very large memory and is also called the free or dynamic pool of memory. This is where large objects can be stored and a programmer needs to make manual allocations during the run time. This is the reason for calling heap memory dynamic.

The size of memory allocation does not need to be decided at the time of compilation or during the execution of the program.

When we talk about programming in C++, a stack acts like a container that stores many variables, similar to an array. Now, with arrays, elements can be accessed and modified in a random order, which is not the case with the stack.

The stack follows the LIFO (Last in First Out) structure, which means that the last item which was pushed to a stack is the first to move out.

Let us understand this with the help of the below-mentioned code:

  void foo1(int a3){
Void foo2(int b2){
    int b1;
static int b3;
int main(){
   int c1;
return 0;

This has been explained in the image below:


At the end of the execution of the following function,

  void foo1(int a3){

The topmost stack (foo1) will be popped out of the stack. The process will continue until the main function is executed and the stack frame is empty. During the termination of the program, the global and static sections will also be freed.

Stack vs Heap in Java

In order to run applications in Java, there is a requirement for some RAM on the computer. This requirement of RAM will keep increasing as and when an object or variable is declared. Partitioning is done in a manner that ensures the application runs quickly.

The process of division of memory between Java Heap space and Java stack memory is done by the JVM, i.e. Java Virtual Machine.

Stack memory in Java

In Java, stack memory is utilized for the allocation of static memory. It has those primitive values which are related particularly to a method and references those objects which are referred from the method in a heap.

As mentioned earlier, memory is accessed in LIFO order, which means when a new method is called, there is a new block that gets created on the top stack and contains values pertaining to that method. At the end of the execution of the method, the corresponding stack frame is freed and space is made available for the next method.

Heap Space in Java

Heap space in Java is utilized for the allocation of dynamic memory to Java objects and JRE classes during run time. It is important to note that new objects will always be created in heap space, but the stack memory stores the references to these objects. It is interesting to note that these objects can be accessed from anywhere in the application.

Also Read =>> An In-Depth Study of Java Heap Data Structure

Let us understand the various generations in which the heap memory model can be divided.

They are mentioned below:

  • Young generation: This is the location for all the new objects to be allocated and aged. When this memory space is full, there is a small garbage collection that takes place.
  • Old or Tenured generation: This is home to those objects which have long survived. There is an age threshold set for objects stored in the young generation and at the end of this threshold, these objects move to the old generation.
  • Permanent generation: This is home to JVM metadata corresponding to runtime classes and application methods.

Let us understand this with the help of a code:

Class Member {
       Int  id; 
       String name; 
        Public member (int id, string name) {
Public class  member builder  {
      Private static  member build member (int id, string name) {
Public static void main (string [ ] args) {
Int id =14;
String name = ‘Smith’; 
Member member= null; 
Member= build member (id, name);

Here, as soon as the main ( ) method is entered, there is a space in the stack memory which is created to store primitives and references pertaining to this method. At the same time, a reference variable member of type Member also gets created in stack memory, which has a corresponding object in heap memory.

As soon as the parameterized constructor Member (int. String) is called from main ( ), memory is created on top of the previous stack. This is where the ‘this’ object reference of the calling object in stack memory is stored along with the primitive value id.

It is important to remember that the reference variable of the argument ‘string name’ will point at that actual string among the string pool created in heap memory.

Next, the main method again calls the building Member ( ) static method, thereby creating more allocation in stack memory on top of the previous one. Heap memory, on the other hand, will be storing the instance variables corresponding to the newly created object ‘Member’ of type Member.

Below is an image to explain this:

stack memory

Here are some frequently asked questions on stack memory vs heap memory.

Frequently Asked Questions

Q #1) What can be stored in heap memory?

Answer: Heap memory, which is also referred to as dynamic memory, is utilized for storing arrays, objects, and global variables.

Q #2) What is the size of the heap?

Answer: The size of the heap depends directly on the physical space available in the system. In order to begin tuning, it is advisable to set the initial and upper limit of heap size at 4096, as the Operating System- 64-bit has address space limited to 4 GB. This does not have any relation to the physical memory available in the system.

Q #3) Why is stack memory faster than heap?

Answer: The process of allocation and deallocation of memory is done basis the access pattern, which makes it a simple process in a stack. However, in heap, there is a complicated process of allocating and freeing up memory.

Q #4) What is stack size?

Answer: Usually, the default size of the main stack is 8 megabytes, however, it is important to remember that stacks are temporary memory addresses that store automatic variables and arguments.


In this article on stack vs heap, we have explained the main points of differences between heap and stack, which will help you make an appropriate choice between the two.

In case the programmers require large size arrays, the heap is a better choice to make. However, if the need of the programmer is limited to the usage of small variables, it is advisable to choose stack over the heap. It is advisable to analyze the needs of programming before a choice is made.