Determing alignment of (char *) pointer

mwm at eris.UUCP mwm at eris.UUCP
Wed Dec 10 21:38:31 AEST 1986


In article <299 at bms-at.UUCP> stuart at bms-at.UUCP (Stuart D. Gathman) writes:
>In article <1510 at mit-trillian.MIT.EDU>, newman at mit-trillian.MIT.EDU (Ron Newman) writes:
>> 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 *).
>
>Cast it to a (long *) and back again then see if it changed.
>
>char *p;
>if ( (char *) (long *) p == p) . . .

As has been pointed out several times, the C compiler isn't guaranteed
to convert p to a valid long* for you. As hasn't yet been pointed out,
many (most?) modern machines are perfectly happy to fetch a long from
an odd boundary; you just pay a performance penalty for it.

So even if your compiler is "correct" (n.b. - the quotes don't mean
that I think this is really correct for C), it could still fail. Worse
yet, some over zealous (and given current memory costs, I'd be tempted
to say not very bright) language maintainer decides that memory is
more precious than CPU cycles, your code could quit working between
compiles.

This brought up an interesting question:

Given a char *p that is not aligned, what should the cast (long *) p
return if it wants to return an aligned pointer? The long containing
*p? The next long after *p? Any standards say anything?

	Thanx,
	<mike



More information about the Comp.lang.c mailing list