Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an array of negative length

Tags:

arrays

c

gcc

c99

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?

like image 213
jonmorgan Avatar asked Sep 23 '10 23:09

jonmorgan


People also ask

Can you declare array size as negative?

Array dimensions cannot have a negative size.

What happens if you pass negative size in array creation?

The NegativeArraySizeException is a runtime exception in Java that occurs when an application attempts to create an array with a negative size. Since the NegativeArraySizeException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

How do you declare the length of an array?

You can declare one-dimensional (1D) arrays with any non-negative size. int [] arr = new int[ 10 ]; // Array of size 10 int [] arr2 = new int[ 100 ]; // Array of size 100 int [] arr3 = new int[ 1 ]; // Array of size 1 int [] arr4 = new int[ 0 ]; // Array of size 0!

Can we declare array with zero size?

Zero-length array declarations are not allowed, even though some compilers offer them as extensions (typically as a pre-C99 implementation of flexible array members).


2 Answers

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.

like image 161
caf Avatar answered Oct 01 '22 14:10

caf


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.

like image 45
Lie Ryan Avatar answered Oct 01 '22 15:10

Lie Ryan