int main(){
int n;
scanf("%d",&n);
int a[n];
}
In the above where does the space for array a[] , get allocated ? In stack or heap ?
int main(){
int n;
scanf("%d",&n);
int a[n];
}
In the above where does the space for array a[] , get allocated ? In stack or heap ?
If your compiler compiles that, it's most likely going to be on the stack. In standard parlance, if you care to apply that to a construct that's not actually standard-conforming, it has automatic storage duration, meaning you don't have to clean it up yourself and it will become invalid at the end of the scope.
What you have there is a VLA (variable length array), a construct from C that allows you to have arrays whose dimensions are known only at runtime. Usually, the way they work is similar to the "function" alloca
, which decreases the stack pointer by an amount known at runtime and "returns" the pointer to it. I put "function" in quotes because doing this requires some low-level hackery that's not provided for by normal function scope semantics.
VLAs don't exist in C++, so you're using a compiler extension, and the precise semantics of VLAs in that extension depend on your compiler. Since this is likely gcc, I'll leave you a link to the relevant part of its documentation.
In the C11 standard, it describes in §6.7.6.2/4 what actually makes an array a variable length array:
If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.
Yet in N3337 (C++11 draft), [dcl.array] says:
If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.
The language about "variable length array"s are completely missing, so they don't exist in C++.
The draft talks about object lifetime in [basic.life]. In C, VLAs cannot have static or thread storage duration. §6.2.4/7 then says:
For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.35) If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.
GCC, which allows VLAs in C++ as an extension, mimics the same semantics:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
Clang also allows VLAs for compatibility with some restrictions.
So more than likely, VLAs are allocated on the stack.
Compiler must know what is the size of all array int the code before execute the project. You cant assign it while the program runs.