Array bounds checking with C????

Dave Gillespie daveg at near.cs.caltech.edu
Sat Sep 1 15:46:30 AEST 1990


>>>>> On 31 Aug 90 14:26:36 GMT, meissner at osf.org (Michael Meissner) said:
> In article <988 at christopher-robin.cs.bham.ac.uk> cjr at cs.bham.ac.uk
> (Chris Ridd <RiddCJ>) writes:
> |   Why is this?  I never could figure out why accessing the first
> | element *past* the end of an array should be legal.

> So that you can do something like:
>       ...
> 	for (p = &array[0]; p < &array[ARRAY_SIZE]; p++)
> 		*p = '\0';

Also, a pointer to the place just past the end of an array must legally
be allowed to exist, for even more innocuous code like:

	p = array;   /* same as "&array[0]" */
	for (i = 0; i < ARRAY_SIZE; i++)
		*p++ = '\0';

Notice that at the end of this loop, "p" points to an address which
would be illegal to access.  But ANSI requires that such a pointer must
work properly, even though saying "*p" or "p++" at this point is
allowed to delete all your files, launch a nuclear strike, or any
other kind of undefined result.  (Whether I would actually buy a
compiler that did this is another story...)

Since I can produce this legal pointer by saying "p++", it stands to
reason I should also be able to say "p = array + ARRAY_SIZE"; and we
all know this is equivalent in C to "p = &array[ARRAY_SIZE]".  It
would be a shame to let these equivalences break just in this one
special case.

								-- Dave
--
Dave Gillespie
  256-80 Caltech Pasadena CA USA 91125
  daveg at csvax.cs.caltech.edu, ...!cit-vax!daveg



More information about the Comp.lang.c mailing list