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. Developers often manage memory manually by using optimal data structure formats. That is why understanding all implications of 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 extensions. The compiler requires these extensions 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, also known as machine-level code, consists of numbers 0 and 1.
The executable file holds all the instructions 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 memory, the program counter generates the program's output. The image below represents the different segments of memory area used in program execution.
In this stack vs heap memory allocation article, first, you will contemplate what stack and heap memory are.
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 variable specified in the program. When the function call is completed, the memory for the variables is released. All of this is accomplished by using 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 running.
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 below does not include any base condition for its recursive call. Due to that, whenever the stack memory gets 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 below explains the stack overflow error scenario in a program shown above.
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 C++, you use new and delete operators for dynamic memory allocation and deallocation. Whereas in C programming language, you use the functions listed below:
The image given below explains how memory allocation is achieved with the help of the malloc() function.
This allocated memory will further be accessed using pointer variable as shown below:
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 when 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); } |
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 more comprehensive learning that 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 catalog can help you improve 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!