[R] aligned memory allocation in C

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 13 08:39:25 CEST 2008


On Tue, 12 Aug 2008, Jeffrey Horner wrote:

> Christophe Dutang1 wrote:
>> Hi,
>> 
>> I'm currently R porting SF Mersenne Twister algorithm of Matsumoto and 
>> Saito. To get the full power of their code, I want to use their fonction 
>> fill_array32 which need aligned memory. That is to say I need to use the C 
>> function memalign on windows, posix_memalign on linux and classic malloc on 
>> Mac OS. In 'writing R extenstion', they recommand to use R_alloc function 
>> to allocate memory in C.
>> 
>> Does R_alloc return a pointer to aligned memory?
>> if not how can I do this?
>> probably no, because R crashes when I succesively R_alloc and fill_array32 
>> (cf below) on my macbook with R 2.7.1.
>
> You can still do this. Just take the address returned from R_alloc and test 
> for alignment. If it's not, then just use an aligned address beyond the one 
> returned.

We haven't been told what the desired alignment is (and those functions 
need to be told).  On 32-bit Mac OS X, R_alloc is definitely aligned on 
4-byte boundaries (on 64-bit OSes it is usually 8-byte aligned).

> (But then the question is, which direction beyond the one returned? How does 
> one test for that?)

Addresses always go upwards.  So if you want 64-byte alignment you need to 
allocate a block at least 64 bytes longer than required, and go up to the 
nearest multiple of 64.

BTW, this is clearly an R-devel question -- see the posting guide.


>
> Jeff
>
>> Thanks in advance
>> 
>> Kind regards
>> 
>> Christophe
>> 
>> 
>> PS : 
>> http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/howto-compile.html 
>> provides an example of memalign.
>> 
>> PPS : mac os report

[removed]

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list