[Rd] transient memory allocation and external pointers

Simon Urbanek simon.urbanek at r-project.org
Mon Apr 19 17:59:09 CEST 2010


On Apr 19, 2010, at 10:39 AM, Melissa Jane Hubisz wrote:

> Hello,
> The Writing R extensions manual section 6.1.1 describes the transient
> memory allocation function R_alloc, and states that memory allocated
> by R_alloc is automatically freed after the .C or .Call function is
> completed.  However, based on my understanding of R's memory handling,
> as well as some test functions I have written, I suspect that this is
> not quite accurate.  If the .Call function returns an external pointer
> to something created with R_alloc, then this object seems to stick
> around after the .Call function is completed, and is subject to
> garbage collection once the external pointer object is removed.
> 

Yes, because the regular rules for the lifetime of an R object apply since it is in fact an R object. It is subject to garbage collection so if you assign it anywhere its lifetime will be tied to that object (in your example EXTPTRSXP).

Although this is true in general (because that is the only way how it can be safely managed by the memory system), I'm not sure it is guaranteed by the API - i.e. it could be changed at any point to an arbitrary memory location which does not necessarily have that semantics. So you can decide to run with it but the fact that this is undocumented means it is not guaranteed to stay that way forever so you may need to change your code if it does.

Cheers,
Simon



> Does anyone know, can I count on this behavior on any platform?  It
> would certainly be useful for me.  ie, Can I create an external
> pointer to something created with R_alloc, and trust that it will not
> be free'd until the external pointer object is removed?  And if so,
> should the manual be edited to describe this behavior?
> Thanks,
> Melissa Hubisz
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
> 



More information about the R-devel mailing list