1

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.

3 Answers 3

5

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++.

Sign up to request clarification or add additional context in comments.

3 Comments

It's vector dynamic? I've heard that vector is comparatively slower
@SuryaK That's premature optimization. Don't do that. std::vector is blazingly fast. If you think not, benchmark it, then come back. Stick to using std::vector now.
@SuryaK "I've heard that vector is comparatively slower" Not significantly if used right. Make use of the initial allocation count, or use reserve().
0

The variable sized array is allocated in the stack.

2 Comments

So, it means it is a bad idea to use VLAs to hold large data and better to use dynamically allocated array or std::vector. Right?
I'd recommend dynamically allocated array over VLAs
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.