"do ... while ((NULL + 1) - 1);" -- valid C?

david.f.prosser dfp at cbnewsl.ATT.COM
Sat Aug 19 00:27:49 AEST 1989


In article <597 at targon.UUCP> ruud at targon.UUCP (Ruud Harmsen) writes:
>I suppose this is machine-dependent because of alignment: char-pointers can
>point to just about anywhere, but int-pointers on many machines have to be
>aligned properly.  My question is: can I make sure in my program, that
>though generally non-portable this IS portable?  I tried this once in the
>following way:
>The char-pointer gets its value from malloc, which the manual says gives
>pointers properly aligned for any type.  I never change that char-pointer
>other than by adding multiples of sizeof(int) to it.
>Is a "ip = cp" guaranteed safe under these conditions, so can I ignore
>the compiler-warning?

Almost.  Strictly speaking, malloc must return a pointer to an object that
can be accessed by a type commensurate with its size in bytes.  For example,
``malloc(1)'' need not return a pointer that is appropriately aligned for a
pointer-to-int.

Moreover, it may well be possible to argue that unless the requested size
is a multiple of the size of an int, the returned pointer need not be
aligned appropriately for an int.  For example, ``malloc(5)''.

However, the rest of your conditions are sufficient for the guarantee of
correct behavior.

Dave Prosser	...not an official X3J11 answer...



More information about the Comp.lang.c mailing list