"do ... while ((NULL + 1) - 1);" -- valid C?
Casper H.S. Dik
casper at betty.fwi.uva.nl
Sun Aug 20 21:32:30 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?
No. It is not safe. If you ever want to run your program on a Data General
MV, among others, you should use "ip = (int *) cp".
Since pointers to anything except char are word aligned on MV machines,
they decided that they could drop the last bit of the address and shift it.
A char pointer pointing to the second byte of memory is represented with
0x2. A word pointer to the same location is represented by 0x1.
This gave problems when porting programs. Most programmers write
"newp = (type *) malloc (sizeof type)"
but many forget the cast to char with free:
"free(oldp)" instead of "free((char *) oldp)"
This works fine in most cases, but not on machines that shift pointers
when casting.
--cd
Casper H.S. Dik VCP/HIP: +31205922022
University of Amsterdam | casper at fwi.uva.nl
The Netherlands | casper%fwi.uva.nl at hp4nl.nluug.nl
More information about the Comp.lang.c
mailing list