簡體   English   中英

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]的2D數組,但是gcc或valgrind對此有所抱怨,並且我得到了正確的輸出(4.0)。 這不是對數組的違反嗎?

如果啟用該警告,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.

您需要更新的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條警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM