Neil Steiner Neil Steiner - 20 days ago 8
C++ Question

C++ dynamically sized static array puzzler

While trying to explain to someone why a C++ static array could not by dynamically sized, I found gcc disagreeing with me. How does the following code even compile, given that the dimension argc of array is not known at compile time?

#include <iostream>
int main(int argc, char* argv[]) {
int array[argc];
for(int i = 0; i < argc; i++) array[i] = argv[i][0];
for(int i = 0; i < argc; i++) std::cout << i << ": " << char(array[i]) << std::endl;
//for(int i = 0; i < 100; i++) { std::cout << i << " "; std::cout.flush(); array[i] = 0; }
return 0;
}


I tested this with gcc 4.2.1, and specified -Wall, without getting so much as a dirty look from the compiler. If I uncomment the last loop, I get a segfault when I assign to array[53].

I had previously placed guard arrays before and after the declaration of array, and had filled them with zeros, certain that the program must be trashing part of its stack, but gcc reordered the variables on the stack, such that I was unable to observe any data corruption.

Obviously I am not trying to get this code to "work." I'm just trying to understand why gcc even thinks it can compile the code. Any hints or explanations would be much appreciated.

Update: Thanks to all for your helpful and ridiculously fast responses!

NPE NPE
Answer

Variable-length arrays (VLAs) are part of C99 and have been supported by gcc for a long time:

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Note that the use of VLAs in C90 and C++ code is non-standard, but is supported by gcc as an extension.