This might seem like a beginner’s question, but I am interested in the way that a compiler normally creates arrays of variable-dimensions, like in the following program.
#include<iostream>
int main(){
int n;
std::cin>>n;
int a[n];
}
From what I’ve learnt, in C all the initializer values must be constant, so that the compiler knows how much memory to reserve inside the function, normally by subtracting the stack pointer in order to accomodate the number of elements the array holds.
This makes sense to me.
However, I don’t quite understand how compilers treat the above program, since it seems to work with G++(MinGW) , but fails with Cl, Microsoft’s C++ compiler. I suspect that GCC allocates memory on the heap trough a non-standard extension, but I am not sure of this.
Also, Microsoft’s compiler is not renowned for being standards-compliant, so I wouldn’t be surprised if it may actually be wrong in the way it treats the above program.
In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you’re seeing a G++ extension. Note that Microsoft’s C compiler does not fully support C99; since G++ supports C99 it’s easy enough to apply the VLA support to C++ as an extension.
As to how the compiler usually implements VLAs, it’s the same as
alloca()(except that it has to keep the size around forsizeof) – the compiler saves the original stack pointer, then adjusts it down by however many bytes it calculates that it needs. The downside is function entry and exit is a bit more complicated as the compiler needs to store where to reset the stack pointer to rather than just adjusting by fixed constants.