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

I have an exam on Tuesday, and I noticed that this question is what my teacher asks a lot in his texts.

At first, I was sure that the correct answer should be “None of them”, since global variables are stored in the data memory, but then I found this book by Robert Lafon called “Object-Oriented Programming in C ++” and in it it’s clearly stated that, according to the C ++ standard, global variables are stored on the heap.Now I’m rather confused and I can’t understand what the correct answer to the asked question is.

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

Thanks in advance.

EDIT: Book Link - Page 231

+5
source share
2 answers

Here is what the book says on page 205:

If you are familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, and global and static variables are stored on the heap.

This is definitely a mistake in the book. First, you should discuss storage in terms of storage duration, as the C ++ standard does: the “stack” refers to the duration of automatic storage, and the “heap” refers to the duration of dynamic storage. Both the “stack” and the “heap” are distribution strategies commonly used to implement objects with appropriate storage lengths.

Global variables have a static storage duration. They are stored in an area that is separate from the heap and stack. Global persistent objects are usually stored in the code segment, while volatile global objects are stored in the data segment.

+12
source

Global variables are not stored on the stack because variables belonging to a function are stored on the stack. Global variables do not belong to any function, so they are stored on the heap.

Here is the best answer to your question: Static and global variable in memory

Edit: now I looked at it more, indeed, there is no specific information from Microsoft where global variables are stored in C ++.

-3
source

Source: https://habr.com/ru/post/1268537/


All Articles