[Rd] Pb with defineVar() example in the "Writing R Extensions" manual

Herve Pages hpages at fhcrc.org
Wed Jan 16 01:49:34 CET 2008


Hi,

I'm wondering if this code from the "Writing R Extensions" manual
is really safe:

     SEXP mkans(double x)
     {
         SEXP ans;
         PROTECT(ans = allocVector(REALSXP, 1));
         REAL(ans)[0] = x;
         UNPROTECT(1);
         return ans;
     }

     double feval(double x, SEXP f, SEXP rho)
     {
         defineVar(install("x"), mkans(x), rho);
         return(REAL(eval(f, rho))[0]);
     }

In C, the order in which function arguments are evaluated before the
function itself is called is undefined. Hence there is no guarantee
that install("x") will be evaluated before mkans(x). What happens if
mkans(x) is evaluated first? Then install("x") will be called and
eventually trigger garbage collection while the SEXP returned by
mkans(x) is still unprotected.

I'm asking because I'm getting all sorts of problems with

  defineVar(install(somekey), mkans(x), rho);

In my code this line is inside a big loop (hundred of thousands of
iterations) so I end up with a lot of symbols in the rho environment.

The problems I've seen are hard to reproduce: sometimes it's a segfault,
sometimes a "cons memory exhausted" error, or sometimes everything looks
fine except that, later, when I retrieve values from the rho environment
with findVar(), some of them are altered!

But if I replace the above line by:

  PROTECT(ans = mkans(x));
  defineVar(install(somekey), ans, rho);
  UNPROTECT(1);

then everything works fine :-)

Cheers,
H.



More information about the R-devel mailing list