2

When memory is allocated dynamically, is it stored on the heap no matter where it was declared? For example, if the following line of code is declared inside main()

int* p = new int[100000];

will memory be allocated from heap or stack?

If the same declaration is made in global scope, memory will be obtained from the heap. But I read that dynamically allocated memory is stored on the heap and local variable are stored on the stack. So when the above line of code is executed from inside of main, which makes it a local variable, will memory be obtained from the stack or heap?

WhatIf
  • 653
  • 2
  • 8
  • 18
  • 1
    Very simple: if you use "new", the memory will be allocated from the heap. "p" is a local variable - it's a pointer, and it's stored on the stack. The 10,000 ints it points to were allocated by "new"; they're stored in the heap. – paulsm4 Oct 12 '15 at 18:19
  • 1
    `p` itself is on the stack. It points to memory allocated in the heap. – interjay Oct 12 '15 at 18:20

2 Answers2

1

I thought I'd make this an answer:

Very simple:

  • If you use "new", the memory will be allocated from the heap.

  • "p" is a local variable. It's a pointer, and it's stored on the stack.

  • The 10,000 ints it points to were allocated by "new"; they're stored in the heap.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
1
int* p = new int[100000];

Will always allocate memory from the heap (correct term is dynamic storage). That's implied using new or new[].

Only the pointer variable itself will get static storage allocation outside of main(), local storage inside respectively.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190