This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Array out of bounds warning


Hi,

the Compaq C compiler has a warning for an array out of bounds access
with constant index (and known array size, of course), like this:

int a[10];
a[10] = 17;

I've already discovered two nasty bugs with this warning, so I
wondered whether it might be worth adding it to gcc. It can be
erroneously triggered with code that allocates extra space after the
array, for example by putting it into a union. These arrays usually
have a size of 1, so the Compaq C compiler has a special warning for
that which can be toggled seperately. I'd rather never warn in this
condition, so I suggest something like this:

--- cvs/gcc/gcc/c-typeck.c	Sun Jul 30 19:23:25 2000
+++ gcc-07.30/gcc/c-typeck.c	Sun Jul 30 21:18:22 2000
@@ -1332,6 +1332,24 @@
 	    pedwarn ("ANSI C forbids subscripting non-lvalue array");
 	}
 
+      if (1)
+	{
+	  if (TREE_CODE (index) == INTEGER_CST)
+	    {
+	      tree range = TYPE_DOMAIN (TREE_TYPE (array));
+	      if (range != 0
+		  && TREE_CODE (TYPE_MAX_VALUE (range)) == INTEGER_CST
+		  && tree_int_cst_lt (TYPE_MAX_VALUE (range), index))
+		{
+		  /* Accesses after the end of arrays of size 0 (gcc
+		     extension) and 1 are likely intentional. */
+		  if (! tree_int_cst_lt (TYPE_MAX_VALUE (range),
+					 build_int_2 (2, 0)))
+		    warning ("array subscript out of range");
+		}
+	    }
+	}
+
       type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (array)));
       rval = build (ARRAY_REF, type, array, index);
       /* Array ref is const/volatile if the array elements are

(this is the first time I hack gcc, so there might be lots of errors
in this code)

So do you think this is a good idea? If so, at which level should it
be activated?

	Falk


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]