Mail Archives: djgpp/1996/06/05/20:02:42
latorre AT ix DOT netcom DOT com wrote:
: 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.
Assuming that un_aligned is a variable of type pointer to something,
you have to explicitly cast the value to long so be allowed to do that
kind of arithmetic with it. (usually only + and - are allowed and they
take sizeof(type) in account). Correct would be something like this:
long un_aligned;
some *aligend;
un_aligned=(long)malloc(size+alignment);
aligned=(some*)((un_aligned+alignment)&~(alignment-1));
And, of course, alignment has to be a power of 2. Well, you could even
put the malloc call into the 2nd expression and get rid of the temp
variable.
bye, Alexander
--
Alexander Lehmann, | "On the Internet,
alex AT hal DOT rhein-main DOT de (plain, MIME, NeXT) | nobody knows
lehmann AT mathematik DOT th-darmstadt DOT de (plain) | you're a dog."
!!CHANGED!! <URL:http://www.mathematik.th-darmstadt.de/~lehmann/>
- Raw text -