public inbox for gcc@gcc.gnu.org
 help / color / mirror / Atom feed
* Array out of bounds warning
@ 2000-07-30 14:16 Falk Hueffner
  2000-07-31  7:11 ` Jeffrey A Law
  0 siblings, 1 reply; 6+ messages in thread
From: Falk Hueffner @ 2000-07-30 14:16 UTC (permalink / raw)
  To: gcc

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

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2000-08-03  0:59 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2000-07-30 14:16 Array out of bounds warning Falk Hueffner
2000-07-31  7:11 ` Jeffrey A Law
2000-07-31 11:19   ` Falk Hueffner
2000-08-02 14:59   ` Kamil Iskra
2000-08-02 18:12     ` Geoff Keating
2000-08-03  0:59       ` Kamil Iskra

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).