Search code examples
c++dynamic-memory-allocation

Dynamic vs Static memory allocation


So you can use the "new" operator to allocate memory dynamically at run-time. But what about the following case:

#include <iostream>

using namespace std;

int main ()
{
    int size;

    cin >> size;

    int a[size];
}

Here the size of the array cannot possibly be known at compile time, and it is determined at run-time. How is this different than dynamically allocated memory?

This question is partly motivated by the statement on this page:

There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of memory using new. The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run, whereas the dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.


Solution

  • This is legal in C, but not C++. However, some C++ compilers allow it as an extension. This question covers that part in more detail.

    It's different than typical dynamic memory allocation in the sense that the memory is allocated on the stack (rather than the heap) and with automatic storage duration (meaning it gets freed automatically at the end of the scope). When execution exits the scope that contains a, it will automatically be freed. This is not the case with memory allocated via new/malloc.

    It's still a form of dynamic memory allocation (obviously, since the memory has to be allocated on the stack dynamically), but it's not the type of dynamic memory allocation people usually mean when using that term.