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!
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.
That's a Variable Length Array, which is part of the C99 standard. It isn't part of C++ though.
You can also use the alloca
function, which also isn't standard C++, but is widely supported:
int main(int argc, char* argv[])
{
int* array = (int*) alloca( argc * sizeof(int) );
array[0] = 123;
// array automatically deallocated here. Don't call free(array)!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With