Determing alignment of (char *) pointer

Henry Spencer henry at utzoo.UUCP
Sat Dec 6 04:25:31 AEST 1986


> In particular, I need to determine whether the pointer is 32-bit
> aligned before attempting to store a long by casting it to a (long *).

Speaking generally, "there ain't no graceful way".

>    if ((long)p & 3) ...

This one will fail badly on any machine which uses a peculiar representation
for "char *", since it assumes that the low-order bits of the pointer are
the low-order bits of the address.  This is likely to be the case on most
fundamentally byte-addressed machines, but it will fall down on things
like the PDP-10, where the simplest form of pointer is a word address and
character addressing sneaks in using higher bits.  The excrement really
hits the fan if character pointers are too large to fit in a long, which
is technically illegal but can happen.  In general, you can't safely assume
anything about what you get when you convert a pointer into a long; to be
portable, such a value must be treated as a magic cookie without meaningful
internal structure.

>    if ((long)(p - (char *) 0) & 3) ...

If I had to pick one, this would be it.  It's a violation of the rules,
unless X3J11 has done something strange (I haven't brought myself up to date
yet), since pointer subtraction is meaningful only within the same array.
It might run into trouble on strangely-built machines (can you say "segments"
six times swiftly?) where memory is not treated as a single array of bytes,
and would be worrisome on machines that use unorthodox representations of
the null pointer.  But I think it's the best that can be done.  Neither of
the casts should be necessary, actually:  the subtraction is already giving
some kind of integer as a result, so & will work unaccompanied, and the 0
turns into a null pointer automatically because of the way it's used.

Whatever you do, make very sure that it is isolated in a single module,
and that the module's potentially machine-dependent nature is documented
properly.
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,decvax,pyramid}!utzoo!henry



More information about the Comp.lang.c mailing list