Variable sized array on the stack [duplicate]

2019-03-06 06:42发布

This question already has an answer here:

It is my understanding that in C and C++ , we create data-structures whose size is known at compile time on the stack and we use the heap (malloc-free / new-delete) for things whose size is not known at compile time and is decided at run-time.Why then , does my g++ compiler allow me to do something like the following code snippet.

int main(void)
{
    int n ;
    cin >> n ; // get the size of array.
    int arr[n] ; // create a variable sized array.
    .... do other stuff ...
}

Specifically , in the case of an array:
An array is assigned a contiguous block of memory on the stack and there are variables above and below it on the stack , so the array's size must be known so that the variable above the array on the stack , the array itself , and the variables below the array on the stack can all fit into memory neatly. How then are variable sized arrays on the stack implemented ? Why are they even necessary? Why can't we just use the heap for variable sized buffers?

EDIT:
I understand from the comments , that C and C++ have different rules regarding whether VLA's are standard or not and also Neil Butterworth's comment that it is generally not a good idea to ask a question about two languages at once. Thank you people , so I am removing the C tag from my question , as I intended to mainly ask about C++ , as evident by the code snippet syntax. Sorry for the confusion , and thanks for the responses.

标签: c++ arrays stack
1条回答
smile是对你的礼貌
2楼-- · 2019-03-06 07:34

They aren't allowed in standard C++, but they are allowed in standard C, and g++ allows them in C++ as well, as a language extension.

How then are variable sized arrays on the stack implemented?

See this question. The gist is that the size (n) gets evaluated and stored in a compiler-generated local variable, and then that much stack space is allocated. There's no law of physics that says the size of a stack variable has to be known at compile-time - it's merely simpler that way.

Why are they even necessary?

They aren't. As you aid, you can do the same thing with dynamic allocation.

Why can't we just use the heap for variable sized buffers?

Stack allocation is more efficient.

查看更多
登录 后发表回答