Array bounds checking with C????

Andrew P. Mullhaupt amull at Morgan.COM
Tue Sep 4 22:57:14 AEST 1990


In article <1589 at redsox.bsw.com>, campbell at redsox.bsw.com (Larry Campbell) writes:
> Are there actually any current compilers out there that are so stupid that
> they generate substantially different code for the following two code fragments?
> 
>     /* Fragment 1 */
>     for (p = array; p < &array[ARRAY_SIZE]; p++)
> 	*p++ = '\0';
> 
>     /* Fragment 2 */
>     for (i = 0; i < ARRAY_SIZE; i++)
> 	array[i] = '\0';

I hope that there are lots of compilers which can tell the difference
between these. "Off by one" in the number of increments is one of the
classic hazards of side effect assignments. (See my still as yet
unposted "for statement considered harmful in C"...) The next problem
can happed if p is of type (char *) and array is type (double[]). On
machines where sizeof(char) != sizeof(double) (and there are one or
two of these ill-behaved monstrosities around...) you don't get the
same result.

But seriously, folks... the exposure to aliasing of the two fragments
is different, and if p is not used carefully subsequent to exiting
the loop, optimization may be lost - i.e. a mere mortal compiler might
not be able to generate the identical code for the kind of loop where
the array is accessed via a pointer alias and the loop calls a function
with either p or array as an argument. (Suppose the source for the
function in the loop is not in the file where the loop is. How is
the compiler supposed to know that a side effect doesn't prevent the
use of a register for the aliased quanitity?)

Later,
Andrew Mullhaupt



More information about the Comp.lang.c mailing list