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

Xref: news2.mv.net comp.os.msdos.djgpp:4635
From: lehmann AT mathematik DOT th-darmstadt DOT de (Alexander Lehmann)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: [?] aligning value returned by calloc/malloc
Date: 5 Jun 1996 18:44:08 GMT
Organization: Technische Hochschule Darmstadt
Lines: 35
Message-ID: <4p4kho$bag@rs18.hrz.th-darmstadt.de>
References: <31B35635 DOT 738 AT ix DOT netcom DOT com>
NNTP-Posting-Host: fb0402.mathematik.th-darmstadt.de
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


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