Search code examples
c++compiler-errorsg++dynamic-memory-allocationstatic-memory-allocation

How a statically-allocated variable-size array works in C++ ?


#include <iostream>

    using namespace std;

    int main(int argc, const char * argv[])
    {

        int size;
        cin >> size;
        int myArray[size]; //this shouldn't compile , right ? 

        return 0;
    }

I thought this wouldn't compile, but it does actually (using the g++ command).

What I found out later is that GCC actually allows variable-size arrays even if by standard C++ doesn't support variable-size arrays, Which is weird ! Because I hear everyone saying that the only way to create a variable-size array is to use dynamic allocation like int* array = new int[size]; or better std::vector. I thought GCC wouldn't allow that piece of code !

Anyway, My theoretical question is, the myArray array is allocated in the heap or stack area ?


Solution

  • That is an extension on the compiler side. How does it work? Well, it works only to some extent.

    The implementation basically moves the stack pointer a quantity that is dependent on the size of the array, and calls the memory in the middle by the name of the array. It only works to some extent because in VLAs the size is not an integral part of the type, which means that many constructs that can be used on regular arrays cannot be done with this type, like for example passing the array to a template by reference... sizeof is usually supplied but implemented as a runtime construct.