a[], *p: if 0 <= p - a < sizeof(a), must p point to an element of a?

Peter da Silva peter at ficc.uu.net
Tue Jan 9 08:27:09 AEST 1990


Here is a real-life example of a system wherein an optimising compiler
could fail to tell whether a pointer pointed into an array: the famous
intel 8086 family.

Suppose a is XXXX:AAAA through XXXX:BBBB (segment XXXX, offset AAAA through
BBBB).

Suppose p is YYYY:CCCC

Suppose AAAA < CCCC < BBBB.

Since pointer subtraction is only defined within an object, the compiler is
free to evaluate !p-a! by comparing only the offset portions of the
address. !p-a! will evaluate to !(CCCC-AAAA)/sizeof *p!, which is positive
and less than !sizeof a/sizeof *a!.

But !p! doesn't even point into the same segment as !a!. More complex,
in 8086 mode segments may overlap, so !p! may actually point into !a!
but in a different place than !a[p-a]!.

There's no way around this for a segmented architecture, except synthesising
your pointer operations. Not a good idea if you want performance.
-- 
 _--_|\  Peter da Silva. +1 713 274 5180. <peter at ficc.uu.net>.
/      \ Also <peter at ficc.lonestar.org> or <peter at sugar.lonestar.org>
\_.--._/
      v  "Have you hugged your wolf today?" `-_-'



More information about the Comp.std.c mailing list