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

后端 未结 1 988
你的背包
你的背包 2020-12-01 03:53

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

相关标签:
1条回答
  • 2020-12-01 04:32

    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.

    0 讨论(0)
提交回复
热议问题