GCC不抱怨数组超出范围

GCC不抱怨数组超出范围,c,arrays,gcc,valgrind,C,Arrays,Gcc,Valgrind,这肯定有什么不对吧 #include <stdio.h> #define NUM 1 #define NUM_SWARMS 3 typedef float coor_t[NUM]; typedef coor_t gBestX_t[NUM_SWARMS]; gBestX_t gBestX; int main() { gBestX[0][1] = 3.0; gBestX[1][1] = 3.0; gBestX[8][1] = 4.0; printf("%f\n"

这肯定有什么不对吧

#include <stdio.h>

#define NUM 1
#define NUM_SWARMS 3

typedef float coor_t[NUM];
typedef coor_t gBestX_t[NUM_SWARMS];

gBestX_t gBestX;

int main()
{
  gBestX[0][1] = 3.0;
  gBestX[1][1] = 3.0;
  gBestX[8][1] = 4.0;

  printf("%f\n", gBestX[8][1]);

  return 0;
}
#包括
#定义NUM 1
#定义NUM_群集3
类型定义浮点数[NUM];
typedef coor_t gBestX_t[NUM_SWARMS];
gBestX_t gBestX;
int main()
{
gBestX[0][1]=3.0;
gBestX[1][1]=3.0;
gBestX[8][1]=4.0;
printf(“%f\n”,gBestX[8][1]);
返回0;
}

在我看来,这是将gBestX创建为大小为[1][3]的2D数组,但gcc或valgrind对此表示不满,我得到了正确的输出(4.0)。这不是对超出范围的数组的违反吗?

您需要一个更新的gcc。我在编译时收到警告:

Bruces MacBook Pro:测试bruce$gcc-o t15 t15.c t15.c:13:4:警告:数组索引1超过了数组的末尾(包含1个元素)[-Warray界限] gBestX[0][1]=3.0; ^ ~ t15.c:9:1:注意:这里声明了数组“gBestX” gBestX_t gBestX; ^ t15.c:14:6:警告:数组索引1超过了数组的末尾(包含1个元素)[-Warray界限] gBestX[1][1]=3.0; ^ ~ t15.c:9:1:注意:这里声明了数组“gBestX” gBestX_t gBestX; ^ t15.c:15:8:警告:数组索引1超过了数组的末尾(包含1个元素)[-Warray界限] gBestX[8][1]=4.0; ^ ~ t15.c:9:1:注意:这里声明了数组“gBestX” gBestX_t gBestX; ^ t15.c:17:25:警告:数组索引1超过了数组的末尾(包含1个元素)[-Warray界限] printf(“%f\n”,gBestX[8][1]); ^ ~ t15.c:9:1:注意:这里声明了数组“gBestX” gBestX_t gBestX; ^
生成4个警告。

gcc仅在启用该警告时对边界发出警告。有关更多详细信息,请参阅手册页:

   -Warray-bounds
   -Warray-bounds=n
       This option is only active when -ftree-vrp is active (default for -O2 and above). It warns about
       subscripts to arrays that are always out of bounds. This warning is enabled by -Wall.

       -Warray-bounds=1
           This is the warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must
           be explicitly requested.

       -Warray-bounds=2
           This warning level also warns about out of bounds access for arrays at the end of a struct and for
           arrays accessed through pointers. This warning level may give a larger number of false positives and
           is deactivated by default.

是的。但是为什么你希望gcc会抱怨呢?(我认为valgrind只检查malloc'ed内存,而不是全局或局部变量)@immibis我想gcc会抱怨数组边界之外的内存访问。@immibis是否有标志或更好的方法来实现这一点,以便如果我的程序出错,它会作为问题出现?我有版本5.2.0。必须添加-O2和-Wall或-Warray边界才能得到警告。见我在Pauli Nieminen回答下的评论。谢谢。我用的是墙,什么也得不到。我现在尝试了-Warray bounds=2,但仍然没有收到任何警告。哦,好吧,当我添加-O2标志时,它会给出警告。谢谢。我还应该注意到,使用-ftree vrp和不使用-O2时,我的问题仍然存在。@wuttadowner注意:gcc不会总是注意到越界数组访问,只是在某些时候。@wuttadowner经常出现,您不应该期望gcc注意到所有越界访问。由于数组索引是常量,所以这种特殊情况可能很容易实现。但是想象一下,如果您有类似于
scanf(“%d”、&index)的东西;printf(“%d”,数组[索引])