Path: utzoo!attcan!uunet!mcvax!hp4nl!janus!betty!casper From: casper@betty.fwi.uva.nl (Casper H.S. Dik) Newsgroups: comp.lang.c Subject: Re: "do ... while ((NULL + 1) - 1);" -- valid C? Message-ID: <781@janus.UUCP> Date: 20 Aug 89 11:32:30 GMT References: <1043@levels.sait.edu.au> <961@virtech.UUCP> <10684@smoke.BRL.MIL> <940@lakesys.UUCP> <18996@mimsy.UUCP> <597@targon.UUCP> Sender: news@janus.UUCP Reply-To: casper@fwi.uva.nl (Casper H.S. Dik) Organization: Faculteit Wiskunde & Informatica, Universiteit van Amsterdam Lines: 36 In article <597@targon.UUCP> ruud@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@fwi.uva.nl The Netherlands | casper%fwi.uva.nl@hp4nl.nluug.nl