Bounds checks. (was variable-length struct hack)

Theo Norvell norvell at csri.toronto.edu
Sat Dec 9 08:18:20 AEST 1989


In article <809 at prles2.UUCP> meulenbr at cstw68.prl.philips.nl (Frans Meulenbroeks) writes:
>(by the way, does ANSI allow index out of
>bound checks? Are they forbidden? Is it left to the implementor? I could
>not find anything in the draft)
>
The drafts were not very explicit on this point, but when I was writing
a compiler that did bounds checks, I read the then current draft
and came to the following conclusion.

Loading or storing out of bounds results in undefined behaviour.  The
standard does not say this directly, but it does say:
	(1) Adding or subtracting from a pointer such that
	    it points outside of the array it is pointing into
	    results in an invalid pointer (I think that is the
	    term used).
	(2) Loading or storing through an invalid pointer is
	    undefined.
Note that forming an invalid pointer is not always undefined.
In the special case of a pointer value that points just past
the end of an array you can still compare with it (consider
int A[N] ; for(p=A; p < A+N; ++p) ... ) and even dereference it
to form a (invalid) lvalue (consider for(p=A; p < &A[N]; ++p) ...
recalling that A[N] is the same as *(A+N)) but you can not load or
store at that lvalue.

Thus the implementor is free to check bounds so long as she is
careful about the one past the end case.  The programmer must
not form pointer values that point out of bounds except for the one past
the end case, and in any case must not load or store via such a pointer.

Theo Norvell



More information about the Comp.std.c mailing list