Is &a[NTHINGS] legal (and the shim)

Dick Dunn rcd at ico.ISC.COM
Tue May 3 16:02:19 AEST 1988


In article <11289 at mimsy.UUCP>, chris at mimsy.UUCP (Chris Torek) writes:
> (Lawrence V. Cipriani) writes:
> >Is it legal to apply the & (address of) operator to an array
> >element that is non-existent?
...
> Yes.  If necessary, the compiler will put a one-byte (or word or
> whatever) shim after the array in that array's address space, so
> that &a[NTHINGS] will be meaningful.

Chris, is this really so?  I understand that &a[NTHINGS] should be valid,
but I don't see why the shim is necessary.  It seems that all you require
is that the address be meaningful and produce correct results on a com-
parison--you can't dereference it because it doesn't exist.

For example, on the 286 (an all-too-frequent counterexample) you can have
contiguous objects up to 2^16 bytes without too much hardship--and since
it is often useful to have arrays of size power-of-two, you might like to
declare, say
	char stuff[65536];
or
	int nonsense[16384];
but you would certainly NOT want the compiler to try to allocate 65537 or
65540 bytes--that just won't work in the normal universe (large model or
less).  There's no reason it should try to do so, however.  It can form an
address &stuff[65536] which is usable for comparison--and address
arithmetic--even though it's not a valid address (nor even a valid segment,
for that matter).

However--here, 286 compiler folks take note--it does require treating
pointer comparison as a 32-bit operation for <, <=, >, >= (not just == and
!=).  The object "stuff" might have an address that looks like 008f0000.
The address of stuff[65535]--the last element--is 008fffff.  The next
valid user-space address (assuming sequential allocation of segments) after 
008fffff is 00970000.  A straightforward calculation of &stuff[65536] will
give 00900000--not a valid address; gives a protection violation from a
user program--but useful for a 32-bit unsigned comparison.
-- 
Dick Dunn      UUCP: {ncar,cbosgd,nbires}!ico!rcd       (303)449-2870
   ...Never attribute to malice what can be adequately explained by stupidity.



More information about the Comp.lang.c mailing list