Process Memory
Learn about stack and heap memory segments in C++ and their differences.
We'll cover the following...
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:
The next sections will provide more details about the stack and the heap, and also explain when we are using each of these memory areas in the C++ programs we write.
Stack memory
The stack differs in many ways compared to the heap. Here are some of the unique properties of the stack:
- The stack is a contiguous memory block.
- It has a fixed maximum size. If a program exceeds the maximum stack size, the program will crash. This condition is called stack overflow.
- The stack memory never becomes fragmented.
- Allocating memory from