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

Edoardo Meneghini picture Edoardo Meneghini · Jun 5, 2017 · Viewed 26.2k times · Source

I have an exam on tuesday and I've noticed that, this question is one that my teacher asks a lot in his texts.

Initially I was pretty sure that the correct answer had to be "None of them", since global variables are stored in the data memory, but then I've found this book from Robert Lafore, called "Object Oriented Programming in C++" and it clearly states that, according to the C++ standard, global variables are stored on the heap. Now I'm pretty confused and can't really figure out what's the correct answer to the question that has been asked.

Why would global variables be stored on the heap? What am I missing?

Thanks in advance.

EDIT: Link to the book - page 231

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jun 5, 2017

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.