Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!csri.toronto.edu!norvell From: norvell@csri.toronto.edu (Theo Norvell) Newsgroups: comp.std.c Subject: Bounds checks. (was variable-length struct hack) Message-ID: <1989Dec8.161820.24804@jarvis.csri.toronto.edu> Date: 8 Dec 89 21:18:20 GMT References: <448@longway.TIC.COM> <450@longway.TIC.COM> <15364@haddock.ima.isc.com> <809@prles2.UUCP> Organization: University of Toronto, CSRI Lines: 31 In article <809@prles2.UUCP> meulenbr@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