Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!mnetor!seismo!mimsy!umd5!brl-adm!brl-smoke!gwyn
From: gwyn@brl-smoke.ARPA (Doug Gwyn )
Newsgroups: comp.lang.c,comp.unix.wizards
Subject: Re: pointer alignment when int != char *
Message-ID: <6061@brl-smoke.ARPA>
Date: Sun, 5-Jul-87 16:33:45 EDT
Article-I.D.: brl-smok.6061
Posted: Sun Jul  5 16:33:45 1987
Date-Received: Sun, 5-Jul-87 22:43:23 EDT
References: <493@its63b.ed.ac.uk>
Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) )
Organization: Ballistic Research Lab (BRL), APG, MD.
Lines: 35
Xref: mnetor comp.lang.c:2836 comp.unix.wizards:3116

In article <493@its63b.ed.ac.uk> simon@its63b.ed.ac.uk (Simon Brown) writes:
>If I were to want to implement malloc (or some such) on a machine where
>sizeof(int) != sizeof(char *), how do I ensure that the pointer-values I
>return are maximally aligned (eg, quad-aligned)? If sizeof(int)==sizeof(char *),
>then I can cast the pointer to an int, do whatever arithmetic stuff is
>required to it to get it to be aligned, then cast it back again - but of
>course this won't work if information is lost by either of the casts.

First, do most of your arithmetic on (char *) data types, not on (int)s.

Second, forcing alignment may require converting your pointers to
integral types to do the rounding operations.  (long) is appropriate
for portable code.  (If a (char *) won't fit into a (long), you have
real problems!)

Third, it is difficult to portably determine alignment requirements.
Consider using something like the following:
	struct align
	{
		char	c0;
		union
		{
			long	l1[2];
			double	d1[2];
			char	*cp1[2];
			union
			{
				long	l2[2];
				double	d2[2];
				char	*cp2[2];
			}	u1[2];
		}	u0;
	}	a;
	#define	ALIGN	((char *)&a.u0 - (char *)&a.c0)
(This example can probably be improved.)