声明一个负长度的数组 [英] Declaring an array of negative length
问题描述
在 C 中创建负长度数组时会发生什么?
What happens in C when you create an array of negative length?
例如:
int n = -35;
int testArray[n];
for(int i = 0; i < 10; i++)
testArray[i]=i+1;
此代码将编译(并且在启用 -Wall 时不会出现警告),而且您似乎可以毫无问题地分配给 testArray[0]
.分配过去会导致段错误或非法指令错误,并从数组中读取任何内容都会说中止陷阱"(我不熟悉那个).我意识到这有点学术性,并且(希望)永远不会出现在现实生活中,但是 C 标准是否有任何特定的方式来处理此类数组,或者它是否因编译器而异?
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?
推荐答案
这是未定义的行为,因为它打破了应该"约束:
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.
这篇关于声明一个负长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!