Statically define an array whose size is known at runtime. Expected/unexpected behavior?

This is related to C/C++ and not directly related to CUDA. Well, it’s part of a CUDA project.

In CS 101 I was taught that statically defined arrays could not depend on something like:

int N=atoi(argv[1]);

float arrayOfFloats[N];

However, both NVCC, for compiling, and GCC 4.6, linking, ate this up and had no complains. Does the compiler cleverly replaces it by a heap allocation?

What is the behavior for this sort of thing, other than the segmentation fault I got. Shouldn’t the compiler complain a-priori?


I had a similar thing on an OpenCL project (my bad) that complained neither at compile nor at runtime on one system, but for other systems crashed. Is unexpected, isn’t it?

I’m not sure what the crashing is related to, but a number of compilers (including GCC) allow static arrays of variable size as an extension to the language. NVCC calls out to GCC for host-side compilation, so I’m not surprised you don’t see any complaints.

(GCC can be run with warning flags turned on that will complain about this kind of non-standard usage.)