What happens in C when you create an array of negative length?
当创建一个长度为负的数组时,C中会发生什么?
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?
这段代码将会编译(并且没有启用-Wall的警告),并且看起来您可以毫无问题地分配给testArray[0]。赋值给过去,要么给出分段错误,要么给出非法的指令错误,并且从数组中读取任何内容都表示“中止陷阱”(我不熟悉这个)。我意识到这有点学术性,并且(希望)在现实生活中永远不会出现,但是C标准是否有任何特定的方法来处理这样的数组,或者它是否因编译器而异?
3 个解决方案
#1
20
It's undefined behaviour, because it breaks a "shall" constraint:
它是未定义的行为,因为它打破了“应该”的约束:
C99 §6.7.5.2:
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.
如果大小不是整数常量表达式……每次计算时,它的值都应该大于零。
#2
3
Undefined behavior, I believe, though don't quote me on that.
不明确的行为,我相信,尽管不要引用我的话。
This gives the error error: size of array 'testArray' is negative
in gcc:
这就产生了误差:在gcc中,'testArray'数组的大小为负:
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.
即使对-Wall和-W都不产生错误。
However, if you use -pedantic flag, gcc will warn that ISO C90 forbids variable length array.
但是,如果您使用-pedantic标志,gcc将警告说ISO C90禁止可变长度数组。
#3
0
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.
Visual studio erro消息用于编译,您可以使用-1表示一个空数组。它期望int并且您正在传递int,所以没有编译错误。
#1
20
It's undefined behaviour, because it breaks a "shall" constraint:
它是未定义的行为,因为它打破了“应该”的约束:
C99 §6.7.5.2:
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.
如果大小不是整数常量表达式……每次计算时,它的值都应该大于零。
#2
3
Undefined behavior, I believe, though don't quote me on that.
不明确的行为,我相信,尽管不要引用我的话。
This gives the error error: size of array 'testArray' is negative
in gcc:
这就产生了误差:在gcc中,'testArray'数组的大小为负:
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.
即使对-Wall和-W都不产生错误。
However, if you use -pedantic flag, gcc will warn that ISO C90 forbids variable length array.
但是,如果您使用-pedantic标志,gcc将警告说ISO C90禁止可变长度数组。
#3
0
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.
Visual studio erro消息用于编译,您可以使用-1表示一个空数组。它期望int并且您正在传递int,所以没有编译错误。