【问题标题】:GCC not complaining about array out of boundsGCC 没有抱怨数组越界
【发布时间】:2015-11-19 02:06:55
【问题描述】:

这肯定有问题吧?

#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] 的 2D 数组,但 gcc 和 valgrind 都在抱怨这一点,我得到了正确的输出 (4.0)。这不是违反数组越界吗?

【问题讨论】:

  • 是的。但是你为什么指望 gcc 抱怨呢? (而且我认为 valgrind 只检查 malloc 的内存,而不是全局或局部变量)
  • @immibis 我想我认为 gcc 会抱怨访问内存超出数组边界。
  • @immibis 是否有一个标志或更好的方法可以做到这一点,以便如果我在我的程序中搞砸了它会成为一个问题?

标签: c arrays gcc valgrind


【解决方案1】:

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.

【讨论】:

  • 我正在使用 -Wall 却一无所获。我现在尝试了 -Warray-bounds=2 仍然没有收到任何警告。
  • 哦,好的,当我添加 -O2 标志时,它会发出警告。谢谢。
  • 我还应该注意,使用 -ftree-vrp 而没有 -O2 我的问题仍然存在。
  • @wuttadowner 注意:gcc 不会总是能够注意到越界的数组访问,只有某些时候。
  • @wuttadowner 通常情况下,您不应该期望 gcc 注意到所有越界访问。这种特殊情况可能很容易,因为数组索引是常量。但是想象一下,如果你有类似scanf("%d", &amp;index); printf("%d", array[index]);
【解决方案2】:

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

Bruces-MacBook-Pro:test 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 个警告。

【讨论】:

  • 我的版本是 5.2.0。
  • 是的,刚刚知道了。必须添加 -O2 和 -Wall 或 -Warray-bounds 才能获得警告。请参阅我在 Pauli Nieminen 的回答下的评论。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2016-08-25
  • 2021-12-22
  • 2012-10-28
  • 1970-01-01
相关资源
最近更新 更多