Modern C++ memory allocation

CMP
8 min readAug 1, 2023

Memory allocation is an important concept for systems programmers to understand, especially when working in environments where resources are limited. This article will go over the differences between the different types of memory allocation and the best practices in modern C++.

Static vs. Dynamic vs. Automatic Memory Allocation

When learning about memory allocation, you may have heard of terms like “the stack” and “the heap”, as well as “static memory” and “dynamic memory”, but what do these terms actually mean?

Memory is split into a few major sections:

  • Text Segment: A read-only section of memory containing executable instructions.
  • Data Segment: A section of memory used to store global and static variables, managed by the compiler. Memory allocated here is known as static memory and the lifetime of these variables are tied to the lifetime of the program.
  • The Stack: A region of memory organized in a last-in-first-out (LIFO) fashion, managed by the operating system and the compiler. The stack pointer (SP) keeps track of the top of The Stack. As functions are called, stack frames are pushed onto The Stack, storing data such as the return address, local variables, and more.

Memory allocated on The Stack is known as automatic memory or “stack memory” and includes local variables for a function. To allocate memory for local variables, the SP simply moves a fixed amount, making stack memory allocation just as fast…

--

--

CMP
CMP

Written by CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.