The importance of showing ALL of the code in C

From: Eric J. Korpela <korpela_at_ssl.berkeley.edu>
Date: Wed Feb 6 16:45:31 2002

> "Fred Cisin (XenoSoft)" wrote:
> > On Wed, 6 Feb 2002, John Chris Wren wrote:
> > > Or it would possibly cause a segfault, since A can only be legally indexed
> > > by 0..9. (This is assuming it didn't get optimized out).
> >
> > No. In C, that is actually NOT considered an error by the language! It's
> > "bad form", but permitted by the language to use array notation to access
> > memory locations that were NOT allocated to the array!

It is not permitted in standard C.

> Thats because array notations are nothing more that pointer arithmetics. That is
> why it is valid. It eventually becomes *(A + 10) which is *VALID* like any other
> pointer operations in C. Of course, this may SEGV in certain systems. I remember
> that * (A - 1) used to have the size of the array that was allocated! Dont know if
> that
> is true today....

It all depends upon what your definition of valid is. If you use "will
compile without error" then any of the above are valid. If you use "is
specified in the language standard as conforming code" then it is definitely
not valid.

IMHO, and according to the C standard, *(A+10) or A[10] are only valid if A[10]
points to a member of the same object as A[0]. *(A-1) is only valid if
*(A-1) and *A are contained in the same object. Compilers will allow a
programmer to violate the standards, but such violations are done at the
expense of portability. Addition of pointers beyond the end of an object
isn't guaranteed to work, even if you don't dereference them.

Eric
Received on Wed Feb 06 2002 - 16:45:31 GMT

This archive was generated by hypermail 2.3.0 : Fri Oct 10 2014 - 23:34:44 BST