Help me cast this!

Bob Henderson hender at prandtl.nas.nasa.gov.nas.nasa.gov
Wed May 4 08:45:43 AEST 1988


In article <294 at fedeva.UUCP> wrd3156 at 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 at 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."



More information about the Comp.lang.c mailing list