2

My understanding is that, to allocate memory to a variable on stack, compiler needs to know its size during the compile time. In case of variable length arrays, as compiler can't figure out the size, I thought the memory is allocated in heap during run time. I printed the address to confirm this -

int main(){
    int n;
    cin>>n;
    int A[n];
    cout<< &n << " "<< A <<endl;
}

The output is

0x7ffc663c9b2c 0x7ffc663c9ae0

They are close to each other => A is on stack. How does the compiler know what size to allocate to array A at compile time?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Sashank
  • 590
  • 7
  • 22
  • This not a valid C++ code. – 101010 Nov 18 '15 at 22:56
  • This is not part of C++. – Baum mit Augen Nov 18 '15 at 22:56
  • 1
    @BaummitAugen IMHO this is arguable since the OP uses input/output streams which they're not C either. – 101010 Nov 18 '15 at 22:57
  • What they are saying is variable length arrays are in standard C but an extension to standard C++. – Anon Mail Nov 18 '15 at 22:58
  • 1
    Duplicate: http://stackoverflow.com/a/737245/864696 – Ross Presser Nov 18 '15 at 22:58
  • *"How does the compiler know what size to allocate to array A at compile time?"* It doesn't, it generates code to allocate memory at run time. – Weather Vane Nov 18 '15 at 23:00
  • @RossPresser I know it is valid in C99. I want to know how the compiler implements it. I did not find it there. – Sashank Nov 18 '15 at 23:01
  • @Sashank the top answer there describes how the compiler implements it – M.M Nov 18 '15 at 23:02
  • @WeatherVane At run time all the stack variables needs to have an address ri8! If compiler generates code to allocate memory at run time, what about other variables in the same scope and are declared after this? – Sashank Nov 18 '15 at 23:03
  • From the answer I linked: >>gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. << This means that the code emitted by gcc will compute the size needed to hold the array, and adjust the stack pointer by that amount. – Ross Presser Nov 18 '15 at 23:04
  • why don't you write some code and look at the assembly output to see for yourself? use `gcc -S` for example. – M.M Nov 18 '15 at 23:05
  • It doesn't. It just generates code to subtract (add) a non-constant from the stack pointer; nothing exciting. `clang -S` or `gcc -S` are a good way to see how it works. – Jason Nov 18 '15 at 23:08

0 Answers0