Path: utzoo!mnetor!uunet!lll-winken!lll-tis!ames!amelia!prandtl.nas.nasa.gov!hender From: hender@prandtl.nas.nasa.gov.nas.nasa.gov (Bob Henderson) Newsgroups: comp.lang.c Subject: Re: Help me cast this! Message-ID: <554@amelia.nas.nasa.gov> Date: 3 May 88 22:45:43 GMT Expires: 30 May 88 07:00:00 GMT References: <294@fedeva.UUCP> Sender: news@amelia.nas.nasa.gov Reply-To: hender@prandtl.nas.nasa.gov (Bob Henderson) Organization: NASA Ames Research Center, Moffett Field, CA Lines: 44 Keywords: pointer to array of struct Summary: Casting malloc correctly In article <294@fedeva.UUCP> wrd3156@fedeva.UUCP (Bill Daniels) writes: > >How do I cast the malloc() in line 12 of the following program to avoid >the lint cries of "warning: illegal pointer combination" et al? >My system is a Perkin-Elmer 3210 running SYS V rel. 2. I have tried >"all but one" of every combination of casts known to mankind. Help me find >the only one left, the one that works! >... Lint is complaining about the assignmemt, not because of the casting, but because it is not sure the byte address returned by malloc will allign the structure correctly. (It most likely will, but link cannot be sure). So the "trick" is to force the alignment to a word boundry. Assuming that "int" is the natural size for your machine; you might code the cast like: struct foo { long count; char byte; int junk; } foo, *pfoo; char *malloc(), *cp; /* step 1: allocate n-1 extra bytes for alignment */ cp = malloc(sizeof(foo)+sizeof(int)-1); /* step 2: align address to natural boundry */ pfoo = (struct foo *)(( (int)cp +sizeof(int)-1) & ~(sizeof(int)-1) ); In step 1, the space is allocated, along with extra space for the allignment. In step 2, the address malloc returned (a byte address) is adjusted to point to the next byte address (inclusive) that is also a int address. If double words or some large address type is involved, then use that type instead of int. ----------------------------------------------------------------------------- Bob Henderson NASA Ames Research Center arpa: hender@prandtl.nas.nasa.gov uucp: {ihnp4,hplabs,ucbcad,tektronix,allegra}!ames!prandtl!hender "I like work; it fascinates me; I can sit and look at it for hours."