The Definitive Guide to Understand Stack vs Heap Memory Allocation

Memory is a crucial resource while developing any software or application. Depending on the preconditions of the hardware, the input flow is designed in each software development strategy. On many occasions, developers manage memory manually by using optimal data structure formats. That is why understanding all implications about memory is essential. So, in this tutorial, you will deal with Stack vs Heap memory allocation in C and C++.

How Does a Program Work?

The C and C++ program files are stored with .c and .cpp extension. These extensions are required for the compiler to recognize that the file is a C/C++ program. When you run a C program, the linker initially connects the program to all included header files. Following that, the loader is put to work. The loader will load the .exe file into RAM and notify the CPU of the starting address at which this program is loaded. This executable file is also known as machine-level code, and it consists of numbers 0 and 1.

Thumbnail_Loader_CandCPP

The executable file holds all the instructions that are required to execute the program. The program counter takes over all those instructions and allocates memory to all the variables, functions, parameters, and return calls. By utilizing the memory, the program counter generates the output of a program. The image given below represents the different segments of memory area used in program execution.

Memory_Segmentation

In this stack vs heap memory allocation article, first, you will contemplate what stack and heap memory are.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Stack Memory Allocation

Stack memory allocation takes place on contiguous blocks of memory. As this allocation occurs in the function called stack, it is commonly referred to it as a stack memory allocation. The compiler calculates how much memory to allocate for each type of variable specified in the program. When the function call is completed, the memory for the variables is released. All of this is accomplished through the use of specified procedures in the compiler. A developer does not have to worry about stack memory allocation and deallocation.

This type of memory allocation is also known as temporary memory allocation. The stack memory area stores local variables, arguments passed through a function, and their return addresses. After the function completes its execution, all of the data belonging to that function is immediately flushed off the stack. This means that any value saved in the stack memory scheme is available as long as the procedure hasn't completed its execution and is still in a running state.

Stack Overflow Error in Programming

The stack size in the computer's memory is restricted. If a program consumes more memory than the stack size, a stack overflow occurs, resulting in a program failure. The program given below does not include any base condition for its recursive call. Due to that, whenever the stack memory gets completely filled, a stack overflow error occurs.

//Stack Overflow

#include<stdio.h>

void fun(int a) {

   if (a== 0)

    return;

    a += 1;

    printf("\n");

    printf("%d",a);

    fun(a);

}

int main() {

   int a = 5;

   fun(a);

}

The simulation given below explains the scenario of stack overflow error in a program shown above. 

Memory_Stack_Stack_Overflow-Stack_vs_Heap.

Heap Memory Allocation

Heaps memory is allocated during the execution of programmers' instructions. It is crucial to highlight that the name heap has nothing to do with the heap data structure. It is termed a heap because it is a collection of memory space that programmers can allocate and deallocate. 

When you construct an object, it is always in Heap-space, and the referencing information for these objects is always saved in Stack-memory. Because the data stored in this region is available or visible to all threads, heap memory allocation is not as safe as stack memory allocation. A memory leak in the application can occur if the programmer does not handle this memory well.

In the C++ programming language, you use new and delete operators for dynamic memory allocation and deallocation. Whereas in C programming language, you use the  functions listed below:

Heap_Allocation-Stack_vs_Heap

The image given below explains how memory allocation is achieved with the help of the malloc() function.

Heap_Memory_Allocation

This allocated memory will further be accessed using pointer variable as shown below:

Heap_Memory_Utilization_Using_Pointer

Heap Overflow Error

In the case of heap memory allocation, the programmer is solely responsible for de-allocating the memory space. Two scenarios mentioned below can lead to heap overflow error:

  • If you allocate the memory continuously and don't release the utilized memory after use, it may cause memory leakage. Memory leakage is a condition in which the memory is unavailable for processes due to previous access. 

//C1 - Heap Overflow [Stack vs Heap]

#include<stdio.h>

#include<stdlib.h>

int main()

{

    for (int i=0; i<1000000000000000000; i++)

    {

       int *z = (int *)malloc(sizeof(int));

    }

}

  • If you dynamically allocate memory space for the vast number of variables.

//C2 - Heap Overflow [Stack vs Heap]

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *ptr = (int *)malloc(sizeof(int)*10000000);

}

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Key Differences: Stack vs Heap

The tabular representation is given below lists key differences between Stack and Heap.

Stack Memory

Heap Memory

This memory space stores static variables

This memory space stores dynamic variables

When allotted (by OS) stack memory gets filled, Stack Overflow error occurs

When allocated (by OS) heap memory gets filled, Heap Overflow error occurs

Data saved on the stack can only be accessed by the owner thread, making it safer

Heap memory is not safest as data stored in Heap-memory is visible to all threads

Stack frame access is easier

Heap frame access is difficult

Potential threat: Shortage of memory

Potential threat: Memory Fragmentation

The excellent locality of reference

The adequate locality of reference

Access time is much faster than Heap memory

Access time is much slower than the stack memory

Conclusion

In this stack vs heap memory allocation tutorial, you explored the differences between stack and heap memory space. You discovered how both these memory areas work. Following this, you looked into the stack overflow and heap overflow errors in programming. In the end, you also listed a few key differences between stack and heap memory.

If you are seeking for more comprehensive learning which goes beyond data structures and encompasses the fundamentals of interactive application development, Simplilearn’s Full Stack Java Developer Master’s program will be precisely suited to you. The courses in the above catalogue can build your chances of getting into a software developer role by assisting you in mastering the craft of software development. So, explore now and get started!

Have any questions about this tutorial on the Stack vs Heap Memory Allocation? If yes, please leave them in the comments section at the bottom of this page; we will respond to them soon!

About the Author

Omkar Prabhakar GhadageOmkar Prabhakar Ghadage

Omkar holds a bachelor's degree in computer science with a machine learning minor. Artificial intelligence and automation are two topics that he's passionate about. Python, R, and C++ are among his programming languages of choice. He enjoys watching web series & indulging in adventurous activities

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.