4

Possible Duplicate:
Dynamic array in Stack?
How do compilers treat variable length arrays

Someone I was tutoring wrote some piece of code that looked like this, that compiled, ran properly and made me feel like a complete C++ beginner in the process:

int main(int argc, char** argv)
{
    int Index=0;
    cin>>Index;
    int Test_array[Index][Index];
    ...
}

Now, I found my answer as to why this works in here: about the array in C

However, I still have an interrogation about the how.

I mean, stack size for blocks of code is supposed to be known ahead of time right? So surely, Test_array can't be stored on the stack...

Does the compiler do a new/malloc-delete/free operation behind the hood to use heap memory for the array?

In that case, would such code throw a bad_alloc exception if not enough memory can be found on the heap?

Community
  • 1
  • 1
Magnitus
  • 278
  • 1
  • 11

1 Answers1

5

The only difference at runtime is that the stack pointer is incremented by a variable offset, not by a constant. "Allocating" memory on the stack involves nothing more than incrementing the stack pointer. Whether the compiler knows or doesn't know this value can affect some optimisations, but it is certainly possible.

As a very rough example the difference is:

add sp <sizeof(int) * 5>

vs

add sp <sizeof(int) * nIndex>

The way to do that before the introduction of VLA-s was with the alloca function.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130