GCC 不抱怨数组越界

GCC not complaining about array out of bounds

这肯定有问题吧?

#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;
}

在我看来,这是将 gBestX 创建为大小为 [1][3] 的二维数组,但 gcc 和 valgrind 都没有抱怨这一点,我得到了正确的输出 (4.0)。这不是数组越界的违规吗?

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

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

gcc 仅在您启用该警告时才发出有关边界的警告。有关详细信息,请参阅 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.