Process Memory

Learn about stack and heap memory segments in C++ and their differences.

Memory segments in C++: stack and heap

The stack and the heap are the two most important memory segments in a C++ program. There is also static storage and thread-local storage, but we will talk more about that later. To be formally correct, C++ doesn’t talk about stack and heap; instead, it talks about the free store, storage classes, and the storage duration of objects. However, since the concepts of stack and heap are widely used in the C++ community, and all the implementations of C++ that we are aware of use a stack to implement function calls and manage the automatic storage of local variables, it is important to understand what stack and heap are.

In this course, we will also use the terms “stack” and “heap” rather than the storage duration of objects. We will use the terms “heap” and “free store” interchangeably and will not make any distinction between them.

The stack and the heap reside in the process’s virtual memory space. A stack is where all the local variables reside; this also includes arguments to functions. The stack grows each time a function is called and contracts when a function returns. Each thread has its own stack, and hence, stack memory can be considered thread-safe. The heap, on the other hand, is a global memory area that is shared among all the threads in a running process. The heap grows when we allocate memory with new (or the C library functions malloc() and calloc()) and contracts when we free the memory with delete (or free()). Usually, the heap starts at a low address and grows in an upward direction, whereas the stack starts at a high address and grows in a downward direction. The figure below shows how the stack and heap grow in opposite directions in a virtual address space:

Get hands-on with 1200+ tech skills courses.