Determing alignment of (char *) pointer
David Eppstein
eppstein at garfield.columbia.edu
Mon Dec 8 05:23:16 AEST 1986
In <7381 at utzoo.UUCP>, henry at utzoo.UUCP (Henry Spencer) writes:
> > if ((long)(p - (char *) 0) & 3) ...
> If I had to pick one, this would be it.
I'm responding to this partly because in his criticism of a different
and worse construction Henry mentioned that it wouldn't work on a PDP-10.
It's been too long since I worked on the relevant compiler, but I
doubt this works on the PDP-10 either. Normal char pointers like p
have word addresses in their low bits and bitfield stuff in their high
bits as Henry said earlier, but (char *)0 is exactly the zero word
(for efficiency in comparisons and for losers who pass it as an
argument without casting it). I don't remember what subtracting one
from the other does but it's probably not what you expect.
Also, the &3 part bothers me. This is ok for the usual char pointers
you see on the PDP-10 because they use 9-bit bytes which pack four to
a word. But 7-bit bytes packed 5 to a word are very common, and I
seem to recall some other architectures having 3 bytes per word (which
can also be done on the PDP-10 but I've never seen it actually used).
The best way to check pointer alignment on the PDP-10 is
(int *) p == (int *) (p - 1) /* unaligned if p-1 is in same word */
which works for all types of byte pointers, but I would go with
p != (char *) (double *) p
since it works for the 9-bit pointers used most often by C and could
be made to work on most other architectures.
Or better rewrite the code to not need this information in the first place.
--
David Eppstein, eppstein at cs.columbia.edu, seismo!columbia!cs!eppstein
More information about the Comp.lang.c
mailing list