Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

EDIT: Link to the book - page 231

like image 211
Edoardo Meneghini Avatar asked Jun 04 '17 23:06

Edoardo Meneghini


People also ask

Are global variables stored in stack or heap C?

The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation.

Are global variables on the stack in C?

Stack and heap are used to store variables during the execution of the program and it also get destroyed. Global data structures or global variables are not consumed by stack or heap.

What variables are stored in stack and heap in C?

The layout consists of a lot of segments, including: stack : stores local variables. heap : dynamic memory for programmer to allocate. data : stores global variables, separated into initialized and uninitialized.

Where local and global variables are stored in C?

Global variables are stored in the data segment of memory. Local variables are stored in a stack in memory.


1 Answers

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.

like image 86
Sergey Kalinichenko Avatar answered Sep 22 '22 18:09

Sergey Kalinichenko