[R] .C() memory allocation

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 5 20:49:46 CET 2003


On Fri, 5 Dec 2003, Dan Davison wrote:

> I would like to retrieve a vector of integers from a call to .C(), but I
> don't know its length in advance. How do I do this without making an ugly
> safe guess?
> 
> My vector is called "sequences".
> I am passing the argument sequences = integer(0) in the call to .C(),
> then declaring the corresponding argument as int *sequences in my C code.
> 
> I tried R_alloc()ing the storage in C and assigning the pointer to
> sequences but that segfaulted.
> 
> Then I tried Realloc()ing sequences:
> sequences = Realloc(sequences, *nsam * *totalnmuts, int) ;
> 
> But that also segfaults.

Yes.  You can't do this with .C, so use .Call instead.

> btw I think this is misleading / a typo in section 5.1.2 p.58 ch5 of
> "Writing R Extensions", I hope I haven't just misunderstood.

> It reads:
> The interface functions are
> 	type* Calloc(size_t n, type)
>  		     ^^^^^^
> 	type* Realloc(any *p, size_t n, type)
>                               ^^^^^^
> 
> But RS.h makes me think that n should just be an integer giving the number
> of elements and not necessarily be of type size_t:

A size_t is a non-negative integer, and it may not be an int (it could
well be larger on a 64-bit machine).  Calloc and Realloc are macros, and
they inform the standard C coercion rules, just as those declarations
imply.

-- 
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