-1

In c++, I know local primary types are allocated on stack, and new a customized class is allocated on heap.

But, what if create a the primary variable via new, is it allocated on heap, or still on stack?

e.g:

function void test() {
  int *pi = new int(1);
}

I knew there is a pointer pi on the function's stack.
But, what about the object it point to (aka *pi), is it on stack or heap?

Wondering is it similar as the primary wrapper type (e.g Integer) from Java.

Eric
  • 22,183
  • 20
  • 145
  • 196
  • The premise of your question shows your understanding is inaccurate. Nothing a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) can't fix. – StoryTeller - Unslander Monica Apr 08 '18 at 08:44
  • What's a primary type? – Mat Apr 08 '18 at 08:45
  • @StoryTeller I am not a c++ programmer, just trying to improve this skill now, thanks for the recommendation. – Eric Apr 08 '18 at 08:46
  • I wasn't really sure exactly what you wanted, but have moved my comment to an answer. – Some programmer dude Apr 08 '18 at 08:49
  • @Someprogrammerdude What I am trying to know is when `new` applied on a primary type in c++, is it similar as the case of primary wrapper type in Java (e.g Integer), and according to your answer, it is. – Eric Apr 08 '18 at 08:54
  • Possible duplicate of [Stack, Static, and Heap in C++](https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c) – Snowhawk Apr 08 '18 at 09:09

1 Answers1

3

For that, two pieces of memory needs to be allocated:

  1. One is created with new, and is on the "heap". This is allocated at run-time.

  2. The other is the storage for the actual variable pi itself, and as it's a local variable the compiler will most likely put it on the stack. This memory on the stack is "allocated" (or rather reserved) at compile-time.

Also note that on a 64-bit system where pointers are 64 bits, the compiler will allocate 8 bytes on the stack for the variable, and then your program allocates 4 bytes on the heap (the size of int is usually 4 bytes).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621