Variable-Sized Arrays on the Stack: Debunking a Programming Myth
The concept of arrays with sizes determined at runtime has long been considered a programming taboo, particularly in C . Common wisdom dictates that only constants can define the sizes of automatic and static arrays. However, a recent code snippet challenges this notion.
Consider the following code:
int main(int argc, char **argv) { size_t size; cin >> size; int array[size]; ... }
Despite the absence of dynamic memory allocation operators such as new or malloc, this code compiles and runs without errors. How is this possible?
The key lies in the C99 standard, which introduced support for variable-sized arrays on the stack. In this case, the compiler allocates the array on the stack dynamically, just like it would with a constant-sized array declared as int array[100].
It's important to note that this is fundamentally different from heap allocation using malloc or new. GCC, in particular, allocates the array on the stack, modifying the stack pointer accordingly. This eliminates the need for heap allocation and resembles the behavior of the _alloca function.
While this construct is not supported in older compilers, it's becoming more prevalent in modern C implementations. It provides a convenient and efficient way to allocate arrays with known sizes at runtime.
The above is the detailed content of Can Variable-Sized Arrays Be Allocated on the Stack in C ?. For more information, please follow other related articles on the PHP Chinese website!