[Rd] Basic Question regarding PROTECT

Duncan Murdoch murdoch at stats.uwo.ca
Mon Aug 24 14:18:25 CEST 2009


On 8/23/2009 11:52 PM, Saptarshi Guha wrote:
> Hello,
> Suppose I have the function
> SEXP foo(){
> SEXP s;
> PROTECT(s=allocVector(...))
> 
> ....
> UNPROTECT(1);
> return(s)
> }
> 
> y=foo() // foo is a recusrive call
> 
> Q: Am i correct in understanding that one does not need to write
> PROTECT(y=foo()) ?(and a corresponding unprotect  later on)
> since it is the object that is protected , SEXP is an alias for
> SEXPREC* and allocVector probably does some memory allocation which
> does not get freed
> when foo returns.

Whether y needs protecting depends on what happens between the y = foo() 
call and the time you return to R.  If nothing happens, i.e. you just 
return y to R, then you're safe.  If you do any memory allocations after 
that call before returning to R then y will need to be protected.

Duncan Murdoch



More information about the R-devel mailing list