[R] Protecting pointer; Rdefines.h

Thomas Lumley tlumley at u.washington.edu
Fri Jul 5 21:42:06 CEST 2002

On Thu, 4 Jul 2002, In-Sun Nam wrote:
> Nonetheless, I wish that you may kindly clarify the concept of garbage
> control; My main problem is that I do not have a clear definition of "R
> heap".
> 1>
>  For example, lets assume that an object "par" is a SEXP to be protected (pg
> 42; Writing R extensions);
> however
> tt = NUMERIC_POINTER(par)[0]
> doesn't need to be. This was one thing that I did not quite understand why.
> So it is because the righthand side is nothing more than a double?

More or less.  par is a numeric vector, an SEXP living on the R heap,
which does need to be protected. If par is protected then its space can't
be reallocated to any other object.  In particular, the space where it
stores the actual numeric values can't be reallocated.  This space is
where tt points.

You only need to protect SEXPs, because anything living on the R heap is
owned by some SEXP and because the garbage collector works by recycling
whole SEXPs.

> 2>
> Another one is that
> " It is a common mistake to believe that if you invoked PROTECT(p) at some
> point then p is protected from then on, but that is not true once a new
> object is assigned to p". (pg 29; Writing R extensions)
> So I don't need to protect "par" again if I reassign
>  NUMERIC_POINTER(par)[0]  = 2.0;
> for example??

Correct.  The important point is that par is still the same SEXP, and so
it is still protected.  Changing the value of its data like this doesn't

Perhaps the best way of thinking about PROTECT is that it applies to R
objects (SEXPs). Don't worry about pointers or the actual C-level
structures, but think of par as actually containing an R object.  That
whole object  needs to be PROTECTed. Once it is PROTECTed it stays that
way until UNPROTECTed.  If you assign a new SEXP to par then the old
value of par is still PROTECTed but the new value may not be.

Every so often the garbage collector comes around and looks at all the
SEXPs on the heap. An SEXP that is not protected will be recycled,
together with all the memory it owns.  This is all managed at the level of
SEXPs -- you don't need to do any memory management at finer levels.


r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list