Surya
Surya

Reputation: 171

Variable lengthed array in gcc

I'm a beginning C++ programmer. So, I just learned that gcc has an extension that allows variably sized array without having to dynamically allocate memory. I want to know if this variably sized array is allocated in the stack or heap.

Upvotes: 1

Views: 59

Answers (3)

IanM_Matrix1
IanM_Matrix1

Reputation: 1594

VLA's are not supported by the C++ standard, although some compilers such as GCC do have them as an extension.

std::vector <> VLA in the GCC implementation.

  • std::vector is resizable and allocates memory on the heap.
  • VLA is not resizable, is limited by the maximum stack size and doesn't allocate memory.

So there is a flexibility difference, and there can be a performance difference especially if the array creation happens regularly (such as in a tight loop).

That said, some of these differences can sometimes be mitigated by for example, moving the 'array' outside of loops etc

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234655

Conceptually it's allocated with automatic storage duration, so in terms of implementation, you can think of it as being on the stack.

Do consider using std::vector as an alternative though as that's standard and therefore portable C++.

Upvotes: 5

Sanjay-sopho
Sanjay-sopho

Reputation: 429

The variable sized array is allocated in the stack.

Upvotes: 0

Related Questions