2

I was reading about Static Memory Allocation and Dynamic Memory Allocation. Static memory is basically int a = 2; where space for a is allocated on stack. But if I do, int * a = new int; *a = 3, here memory is allocated on heap. But then, can the former also be called as automatic memory allocation? Thanks!

John Lui
  • 1,324
  • 18
  • 35
  • the "former" is two instructions. do you mean `int * a = new int;`? There is automatic allocation for the `int *` variable – UmNyobe Jul 17 '15 at 13:49
  • Read up on [storage duration](http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration). – Captain Obvlious Jul 17 '15 at 13:49

1 Answers1

7

Forget about stack and heap. These terms are not defined in the C++ standard (except for things like stack unwinding and std::stack). What you are talking about is storage duration, which can be:

  • static
  • thread
  • automatic
  • dynamic

Dynamic storage duration is applied to objects created using new. Such objects live until you delete them.

Automatic is for block-scope variables not declared static or extern, like local variables in a function. These are automatically (aptly) destroyed when the block ends.

Thread is for variables declared thread_local. These exist until the thread in which they were created finishes.

Static is for anything else, generally variables declared at the file scope or with the static keyword. Such variables exist for the duration of the program.

TartanLlama
  • 59,364
  • 11
  • 141
  • 183
  • Understood, but just asking, isn't it right that when I allocate memory using `new`, it's allocated on heap and when I go for automatic, it's allocated on stack? – John Lui Jul 17 '15 at 13:53
  • No. When you allocate using `new`, memory is allocated with the *free store*. When you have automatic storage, it could be on the stack, it could be optimized out, it could be stored in a register... – TartanLlama Jul 17 '15 at 13:57
  • As a practical matter (common behavior on reasonable architectures), it is useful to think about automatic allocations being in the stack, and allocations with `new` or `malloc` being in the heap. You should be aware that the standard does not enforce that. But understanding the common behavior can still help you in coding well and as an approximation toward the behavior the standard does specify. – JSF Jul 17 '15 at 14:31