Stack and Heap in C++

In computing, Stack and Heap are used for dynamic memory allocation. In this article, I will introduce you to the concept of stack and heap in C ++ programming language.

The task of responding to an allocation request is to locate a block of unused memory of sufficient size is known as dynamic memory allocation. Stack and heap are two areas of dynamic memory allocation.

Also, Read – 100+ Machine Learning Projects Solved and Explained.

Stack and Heap

Stack Memory Allocation:

Stacks in computer architectures are regions of memory in which data is added or deleted on a last-in, first-out basis. In most modern computer systems, each thread has a reserved region of memory called its stack.

The stack is used to store your local variables and is used to pass arguments to functions with the return address of the instruction that should be executed after the function call. When a new stack frame needs to be added, the stack expands downward.

Memory is allocated on the function call stack. The memory is deallocated as soon as the function call is finished. Deallocation is managed by the compiler.

Heap Memory Allocation:

The heap contains a linked list of used and free blocks. New allocations on the heap (by new or malloc) are satisfied by creating an appropriate block from one of the free blocks. This requires updating the block list on the heap. This on-the-heap block meta-information is also stored on the heap often in a small area directly in front of each block.

When the program allocates memory at run time using the calloc and malloc function, the memory is allocated in the heap. when a little more memory needs to be allocated using the calloc and malloc function, the heap grows up.

Allocation takes place on the stack of memory space available to programmers for allocation and deallocation. The programmer must manage the deallocation.


Both stack and heap implementation generally depends on the runtime / operating system. Often, games and other performance-critical applications create their memory solutions that reclaim a large portion of memory from the heap and distribute it internally to avoid relying on the operating system for memory.

Hope you liked this article on the concept of Stack and Heap in C ++ programming language. Please feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1535

Leave a Reply