What happens to array storage?

Possible duplicate:
Dynamic array on stack?
How compilers handle variable-length arrays

Someone I taught wrote some piece of code that looked like this: it compiled, worked correctly, and made me feel like a complete C ++ newbie in this process:

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

Now I have found the answer to the question why this works here: about an array in C

However, I still have a survey on how.

I mean, should the stack size for code blocks be known in advance? So, of course, Test_array cannot be stored on the stack ...

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

In that case, if such code throws a bad_alloc exception, if enough memory is not found in the heap?

+4
source share
1 answer

The only difference at run time is that the stack pointer is incremented by offsetting the variable, not the constant. The โ€œallocationโ€ of memory on the stack no more than increases the stack pointer. Whether the compiler knows or does not know this value may affect some optimizations, but it is certainly possible.

As a very crude example, the difference is as follows:

 add sp <sizeof(int) * 5> 

vs

 add sp <sizeof(int) * nIndex> 

The way to do this before introducing VLA-s was using the alloca function.

+5
source

Source: https://habr.com/ru/post/1381698/


All Articles