tags:

views:

140

answers:

3

What happens in C when you create an array of negative length?

For instance:

int n = -35;

int testArray[n];

for(int i = 0; i < 10; i++)
    testArray[i]=i+1;

This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign to testArray[0] without issue. Assigning past that gives either a segfault or illegal instruction error, and reading anything from the array says "Abort trap" (I'm not familiar with that one). I realize this is somewhat academic, and would (hopefully) never come up in real life, but is there any particular way that the C standard says to treat such arrays, or is does it vary from compiler to compiler?

+2  A: 

Undefined behavior, I believe, though don't quote me on that.

This gives the error error: size of array 'testArray' is negative in gcc:

int testArray[-35];

though, as you've seen:

int n = -35;
int testArray[n];

does not give an error even with both -Wall and -W.

However, if you use -pedantic flag, gcc will warn that ISO C90 forbids variable length array.

Lie Ryan
What does it actually do? I'm guessing it interprets it as unsigned so you get (MAX_INT-35)
Martin Beckett
@Martin Beckett: since it's undefined behavior, compilers are free to do anything, even if they're unreasonable behavior, since allocating a negative length array is a compilable nonsense. If I were to be allowed to redesign C, I'd make array length declaration and indexing an 'unsigned int', and compiler will be required to emit type error when 'signed int' is used for length or indexing operations.
Lie Ryan
@Lie: the question was tagged C99, so the aspect of variable length array is ok from a standards point of view.
Jens Gustedt
A: 

Visual studio erro message for compilation, you can use -1 to say an empty array. It expects int and you are passing int, so no compiler error.

yadab
+7  A: 

It's undefined behaviour, because it breaks a "shall" constraint:

C99 §6.7.5.2:

If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.

caf
Thanks! That's exactly what I was looking for.
spookyjon
@caf: +1, exactly the answer. But I find it quite disappointing that compilers are not yet able to do a static analysis of this sort of code and emit at least a warning. I tested also with `clang` and `-analyse`, not better.
Jens Gustedt