www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/06/05/02:39:10

From: j DOT aldrich6 AT genie DOT com
Message-Id: <199606050615.AA022535358@relay1.geis.com>
Date: Wed, 5 Jun 96 06:26:00 UTC 0000
To: djgpp AT delorie DOT com
Mime-Version: 1.0
Subject: Re: [?] aligning value returne

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 ?

Well, it looks like a valid expression, but you could try telling us
what error message you got.  Was it about typecasting of
pointers to ints or vice versa?  Also, I hope you're working with
a char pointer, because anything else would perform arithmetic
using the pointed-to type size, which could get very nasty.  To
be precise, a char pointer does too, but chars are 1 byte.
Just looking at the expression, I can't figure out how exactly
it is supposed to do what you want it to anyway.  If the address
were already aligned, you'd just be adding 1K to it, which can't
be what you intended.

Besides, wouldn't this work much more elegantly?

aligned = (char *) ( (unsigned) un_aligned + (unsigned) un_aligned % alignment
);

You should use typecasts here to guarantee that you get the correct
operations, _especially_ if your pointer is to something other than char.

Just out of curiosity, why exactly do you want to align your data on such
a large boundary anyway?  GNU C has ways to specify the alignment of
variables and structures, and malloc() under DJGPP performs some
basic alignment itself (it rounds all memory requests up to the nearest
power of 2).

hth,

John

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019