Question

#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 ?

Was it helpful?

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.

OTHER TIPS

myArray in your example is allocated on the stack. g++ has an extension that allows this trick. The heap isn't necessary to do this, the compiler just generates code to increase the stack pointer by an amount that is computed at run time.

VLAs are an extension, many implementations have there own extensions to the C++ language. If you want g++ to complain that you are not adhering to the standard, pass -pedantic flag. VLAs are on the stack which is really fast, however, this is also the cause of problems since you have limited stack space. In C++ however, we have constructs like std::vector, etc., so there is really no need for there use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top