How does this example compile and run?
#include <iostream>
int main() {
int input;
std::cin >> input;
int arr[input];
return 0;
}
My understanding is that since the input
's value is not known during compile time, it'd have to be a heap allocated array. Isn't the stack space for things like arrays (without allocating on the heap) allocated when the program starts?
My understanding is that since the input's value is not known during compile time, it'd have to be a heap allocated array.
While the C++ language rules do indeed say that you can’t do this, from a technical perspective about how the call stack is typically implemented this actually isn’t necessarily true. Generally, yes, objects that don’t have a size known in advance aren’t put on the stack. However, in the case of a local variable that’s an array of variable length, it’s not that hard for the compiler to put that array in stack space. For example, the C language supports this, and this older question addresses one way of implementing it. Even though C++ doesn’t allow for variable-length arrays the way C does (technically speaking what you have here isn’t legal C++ code), some compilers allow for it.
Isn't the stack space for things like arrays (without allocating on the heap) allocated when the program starts?
This usually isn’t the case. When the program starts up, it’s allocated a region of memory and told “this is where your stack should go,” but that space is typically not determined by anything about how the program is written and is usually controlled by the OS or set by the compiler. Then, whenever space on the stack is needed - say, because a function is called or because a new block scope is entered - the program takes up some space on the call stack, handing it back when the block scope exits or the function returns.
As a result, the program doesn’t need to know at the point where it starts how much space to reserve on the stack for each function. It can defer that until the actual functions are called.