Memory Model of a Program
Explore the C++ memory model focusing on stack and heap memory regions. Understand how variables are stored, their lifetimes, and the performance implications of contiguous memory. Learn the advantages and limitations of automatic storage on the stack versus dynamic allocation on the heap, so you can manage memory efficiently and avoid common pitfalls like memory leaks and stack overflow.
We have spent the last few lessons declaring variables, initializing arrays, and calling functions. In every case, we trusted the system to handle the storage. We created an integer, and it existed. We returned from a function, and its local variables vanished. But where did they go? And why did they disappear?
In interpreted languages, memory is often an abstract concept managed entirely by a background garbage collector. You rarely need to think about where a number lives. C++ is different. It gives you direct control over memory, allowing you to choose exactly how long an object lives and where it is stored. This control is the source of C++’s immense performance, but it requires a clear mental model of the computer’s memory layout.
The C++ memory model
When a C++ program runs, the operating system allocates a block of memory for it. This memory is not just a uniform bucket of bytes; it is divided ...