The relevant quote from the book is on page 205:
If you’re familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.
This is simply wrong because global variables are typically stored in a static memory section such as .data
, or .bss
, and these sections are allocated during program startup, not dynamically through e.g. std::malloc
.
Furthermore, the C++ standard doesn't say anything about the stack or the heap; the C++ standard only concerns itself with storage duration, i.e. when storage is obtained and released for an object. Allocation strategy is the way that the implementation allocates storage when it is needed. Here is how the two concepts correspond:
Storage Duration |
Usual Allocation Strategy |
Common Optimizations |
static storage duration e.g. global int , local static int , etc. |
static memory section, e.g. .data , .rodata , .bss |
no memory, only register for global constants, especially constexpr |
thread storage duration , anythingthread_local |
TLS (thread-local storage) |
|
automatic storage duration, i.e. local int , function parameters, etc. |
stack memory |
very often optimized to use only registers, especially for small types like int and float |
dynamic storage duration, i.e. storage was obtained via std::malloc , new , etc. |
heap memory |
heap elision if possible, i.e. use registers instead (powerful compiler needed, optimization can often not be applied) |
Of course, one common optimization I haven't yet mentioned is that if the compiler can tell that any object is unused, it can also completely remove it.
In that case, a global variable is not stored anywhere, it just disappears.