0
int main() {
 int *g = new int;
}

In the example above, *g is allocated dynamically on the heap and is module-global. Is that correct? And what about g? Is it also allocated dynamically on the heap and module-global?

Thank you for answering.

  • 2
    `g` has automatic storage duration. – drescherjm Jul 20 '20 at 18:34
  • 2
    Technically the words stack and heap do not exist in the c++ language. Related: [https://stackoverflow.com/questions/9181782/why-are-the-terms-automatic-and-dynamic-preferred-over-the-terms-stack-and](https://stackoverflow.com/questions/9181782/why-are-the-terms-automatic-and-dynamic-preferred-over-the-terms-stack-and) – drescherjm Jul 20 '20 at 18:36
  • 1
    Speaking non-technically `g` is just a regular stack allocated variable. That's the thing about pointers, the pointer and the thing it points to are two different things. Beginners often get confused about that. – john Jul 20 '20 at 18:40

1 Answers1

2

First of all, the only variable you have is g, which has type int*. There is no g* or *g.

g is allocated dynamically on the heap ... Is that correct?

Not quiet. Memory allocation will happen on the right side of the =. g will be pointing to this newly allocated memory. You can access the allocated memory using g. When the scope ends, g will be destroyed without freeing the memory.

module-global?

No. And we don't have module globals in C++. We have static, automatic, dynamic and thread. g variable in this case is automatic, which basically means it will be destroyed as soon as the scope ends.

Waqar
  • 8,558
  • 4
  • 35
  • 43