Reputation: 374
Surely there is something wrong with this right?
#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;
}
In my mind this is creating gBestX as a 2D array of size [1][3] but yet gcc nor valgrind is complaining about this and I get the correct output (4.0). Is this not a violation of an array out of bounds?
Upvotes: 0
Views: 2932
Reputation: 1120
gcc only warns about bounds if you enable that warning. See gcc man page for more details:
-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.
Upvotes: 3
Reputation: 2513
You need a newer gcc. I get warnings when I compile:
Bruces-MacBook-Pro:test bruce$ gcc -o t15 t15.c t15.c:13:4: warning: array index 1 is past the end of the array (which contains 1 element) [-Warray-bounds] gBestX[0][1] = 3.0; ^ ~ t15.c:9:1: note: array 'gBestX' declared here gBestX_t gBestX; ^ t15.c:14:6: warning: array index 1 is past the end of the array (which contains 1 element) [-Warray-bounds] gBestX[1][1] = 3.0; ^ ~ t15.c:9:1: note: array 'gBestX' declared here gBestX_t gBestX; ^ t15.c:15:8: warning: array index 1 is past the end of the array (which contains 1 element) [-Warray-bounds] gBestX[8][1] = 4.0; ^ ~ t15.c:9:1: note: array 'gBestX' declared here gBestX_t gBestX; ^ t15.c:17:25: warning: array index 1 is past the end of the array (which contains 1 element) [-Warray-bounds] printf("%f\n", gBestX[8][1]); ^ ~ t15.c:9:1: note: array 'gBestX' declared here gBestX_t gBestX; ^ 4 warnings generated.
Upvotes: 0