variable length arrays VLA (static binding or dynamic)

arrays, c, c++

Solution

Does that makes array dynamic?

It depends how you define "dynamic". VLA certainly cannot grow or shrink or, in other words, change its size once it is created. It is dynamic, though, in a sense that its length is not known in compile-time.

Is this memory allocated at heap?

How the memory is allocated for the VLA is implementation specific. Generally speaking, the memory for the VLA is allocated from space in the stack frame of the caller. It is then automatically freed when the function where VLA is defined returns to its caller, or if VLA goes out of scope.

The closest relative of VLA is `alloca()` function, which pretty much can be considered to have the same effect, at least in C. Assuming that compiler implements the VLA the same way `alloca()` is implemented, you can think of these two arrays as being technically the same in C:

int *a = alloca(sizeof(int) * N);
int b[N];

The VLA has, however, more compact and convenient syntax. But most importantly, VLA by nature has an automatic storage duration and gives compiler more freedom to decide whether to destroy/free the array upon leaving the scope where it was declared, or upon returning from the function.

This becomes very important in languages such as C++ where compiler implements RAII idiom and must guarantee to destroy objects with automatic storage duration upon exiting their scope.

Note, however, that VLA is not currently a part of C++ language and is implemented by compiler as a non-standard extension. But they are expected to become standard in C++14.

Problem

It has been a long time since I have programmed in basic compilers with basic arrays, but recently I saw an array declaration like this: ``` int y; cin>>y; int z[y]; ``` old time compilers used to give error "Storage size of array isn't constant". Then I found out about variable size arrays in C99. I wonder how they work internally. Does that makes array dynamic? Is this memory allocated at heap? Does this binding is still done statically? If so how.

Original source

Related problems