Determing alignment of (char *) pointer
rushfort at esunix.UUCP
rushfort at esunix.UUCP
Wed Dec 10 09:12:18 AEST 1986
In article <487 at cartan.Berkeley.EDU> desj at brahms (David desJardins) writes
> Why not use
>
> if (p != (char *) (long *) p) ... ?
>
> This should give you the relevant information (can a long be stored at
>the location pointed to by p?) without any machine dependencies. I suppose
>on some (broken) compilers it might not work...
Not quite. This test merely checks whether casting a character pointer into a
long pointer and then back into a character pointer preserves all of the bits.
A compiler is not forced to check alignment on casts. According to K&R
Appendix A, Section 14.4 (Explicit pointer conversions):
Certain conversions involving pointers are permitted but have
implementation-dependent aspects.
[...]
A pointer to one type may be converted to a pointer to another
type. The resulting pointer may cause addressing exceptions
upon use if the subject pointer does not refer to an object
suitably aligned in storage.
Note that K&R specifically allows an implementation to leave a pointer
alone when casting between pointer types. I tried this out on a VAX
running Ultrix 1.2 and a SUN 2 running some form of 4.2 BSD and both
chose to leave a mis-aligned pointer alone. The bottom line is that
there is no PORTABLE way to determine whether a character pointer is
suitably aligned such that it can point to an object of a different
type.
--
Kevin C. Rushforth
Evans & Sutherland Computer Corporation
UUCP Address: {ihnp4,decvax}!decwrl!esunix!rushfort
Alternate: {ihnp4,seismo}!utah-cs!utah-gr!uplherc!esunix!rushfort
More information about the Comp.lang.c
mailing list