From: kagel AT quasar DOT bloomberg DOT com Date: Wed, 5 Jun 1996 09:15:19 -0400 Message-Id: <9606051315.AA03934@quasar.bloomberg.com > To: j DOT aldrich6 AT genie DOT com Cc: djgpp AT delorie DOT com In-Reply-To: <199606050615.AA022535358@relay1.geis.com> (j.aldrich6@genie.com) Subject: Re: [?] aligning value returne Reply-To: kagel AT dg1 DOT bloomberg DOT com From: j DOT aldrich6 AT genie DOT com Date: Wed, 5 Jun 96 06:26:00 UTC 0000 Reply to message 9879136 from LATORRE AT IX DOT NE on 06/03/96 5:16PM >How do I align the value returned by calloc/malloc on a particular byte >boundry ? For instance 64 or 128. > >I saw something like this, >1: size = 1024 >2: alignment = 128 >3: un_aligned = malloc( size+alignment ) >4: aligned = (un_aligned+size)&~(alignment-1) > >but could not get 4 to compile. > >Any thoughts ? [SNIP] Besides, wouldn't this work much more elegantly? aligned = (char *) ( (unsigned) un_aligned + (unsigned) un_aligned % alignment ); Almost. Try: MYTYPE *aligned, *unaligned; /* Or some reasonable typedef. */ aligned = (MYTYPE *)((unsigned)un_aligned +(unsigned)alignment /*Advance pointer alignment */ /*Backup by #misaligned bytes*/ -((unsigned)un_aligned % (unsigned)alignment)); You want to advance the pointer to the next higher aligned address. This simple code, as suggested by John Aldrich with correction, is clearer than the '&~' code M. Latorre came up with and the optimizer should do a good job at making it efficient. [SNIP] -- Art S. Kagel, kagel AT quasar DOT bloomberg DOT com A proverb is no proverb to you 'till life has illustrated it. -- John Keats