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
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++.
3 Comments
std::vector is blazingly fast. If you think not, benchmark it, then come back. Stick to using std::vector now.reserve().The variable sized array is allocated in the stack.
2 Comments
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