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

brnstnd at stealth.acf.nyu.edu brnstnd at stealth.acf.nyu.edu
Sun Jan 7 05:27:30 AEST 1990


In article <1990Jan5.040710.23691 at twwells.com> bill at twwells.com (T. William Wells) writes:
> In article <875 at stealth.acf.nyu.edu> brnstnd at stealth.acf.nyu.edu (Dan Bernstein) writes:
> : Basically, I want to have a guaranteed test of whether p points to an
> : element of a, with foo a[N] and foo *p. I know that *if* p points to an
> : element of a, *then* 0 <= p - a < sizeof(a); is the reverse true? (If
> : yes, please explain the logic.)
> No. In general, if p does not point to a member of a, p - a is
> undefined.

That doesn't answer the question!

Take a program that computes p - a. There are four possible results for
one run of the program on one machine under one compiler:

  1. FPE is generated.
  2. SEGV is generated.
  3. p - a is between 0 and sizeof(a)/sizeof(*a) - 1 inclusive.
  4. p - a is outside that range.

The standard specifies that if p points to an element of a, then the
result is 3. Also, if p points just past a, then the result is 4.
Otherwise, as you point out, the result is undefined.

My question is about the opposite direction. If cases 1, 2, or 4 happen,
then a conforming program can safely conclude that p does not point to
an element of a. I want to complete that test.

ANSI saw fit to specify that a*(a/b)+(a%b) equals a for any numbers a
and b, provided that a/b doesn't generate a signal. Could they specify
that a + (p - a) equals p for pointers a and p, provided that p - a
doesn't generate a signal? This would make pointer subtraction slightly
slower on most machines: after subtracting the machine values of p and
a and dividing by the size of the type, the code would have to generate
a signal if the division wasn't exact. ANSI has always sacrificed
efficiency for consistency; why not here?

> : The standard should define pointer subtraction more carefully.
> It has defined this most explicitly. Since my fingers are tired,
> I won't type in the appropriate text. But it is in section 3.3.6.

It doesn't define pointer subtraction well enough to answer my questions.

---Dan



More information about the Comp.std.c mailing list