Are global variables in C++ stored on the stack, heap or neither of them?

Here is what the book says 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 definitely an error in the book. First, one should discuss storage in terms of storage duration, the way C++ standard does: “stack” refers to automatic storage duration, while “heap” refers to dynamic storage duration. Both “stack” and “heap” are allocation strategies, commonly used to implement objects with their respective storage durations.

Global variables have static storage duration. They are stored in an area that is separate from both “heap” and “stack”. Global constant objects are usually stored in “code” segment, while non-constant global objects are stored in the “data” segment.

Leave a Comment