3

I want to get something clear that I found most sources so confusing.

For example,

int *a=new int;

Is "a" in stack or heap, and what about "*a"? Most sources I found only refer to heap, I really need an extremely concrete answer. I would be really grateful.

Tjh Thon
  • 85
  • 7

2 Answers2

8

a is in the stack. When the scope of a ends, a is not usable.

*a is in the heap. Even after the scope of a ends, the object that a points to continues to live unless the memory is deallocated before that.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Apart from where on the stack or heap, you should think about it in a c++ way, and that is by considering its storage duration. For example, the global new operator can be overloaded to do whatever. Maybe the object you are being returned is not on the heap or the stack, but is created in global or some specific device memory.

a has automatic storage duration. Which means:

The storage for the object is allocated at the beginning of the enclosing code block and deallocated at the end.

The object created by new int has dynamic storage duration:

The storage for the object is allocated and deallocated per request by using dynamic memory allocation functions.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175