Array bounds checking with C????

Karl Heuer karl at haddock.ima.isc.com
Fri Aug 31 08:54:37 AEST 1990


In article <1990Aug30.134537.26326 at diku.dk> njk at diku.dk (Niels J|rgen Kruse) writes:
>Assume the following code [on a bounds-checking implementation]:
>        char *a,*c; double *b,d[17/sizeof(double)];
>        if (a = malloc (17)) {
>          b = (double *)a;
>          c = (char *)b;
>Is c[16] legal?

I believe it is, and therefore that the cast to (double *) must not actually
reduce the known range of the pointer to that which is pointable from a
double.  Thus, a bounds-checking C implementation must maintain the bounds of
a pointer by using a byte count (or byte pointer) rather than an object count
(or object pointer).

>What kind of object is b pointing to?  How does it differ from
>the object pointed to by (d+0)?

Assume for concreteness that sizeof(double)==8.  Then b is <double *, pointer
to beginning of 17-byte block>, which is room for 2 doubles plus a spare byte
at the end that cannot be referenced without casting b.  But d is <double *,
pointer to beginning of 16-byte block>, which is room for 2 doubles exactly.

>What does your bounds-checking C compiler have to say?
>What does the standard say?

This is my interpretation of the Standard.  I don't have a bounds-checking C
compiler at hand, and I wonder if it would get this right.  (Particularly on a
word-addressible architecture.)

Karl W. Z. Heuer (karl at kelp.ima.isc.com or ima!kelp!karl), The Walking Lint



More information about the Comp.lang.c mailing list