From radford at cs.toronto.edu  Fri Jun 27 11:23:48 2014
From: radford at cs.toronto.edu (Radford Neal)
Date: Fri, 27 Jun 2014 05:23:48 -0400
Subject: [Rd] Need help on calling Head from C
In-Reply-To: <53AC997E.2070706@fhcrc.org>
References: <20140626203624.GA17415@cs.toronto.edu>
	<53AC997E.2070706@fhcrc.org>
Message-ID: <20140627092348.GA23738@cs.toronto.edu>

> >The code is actually not safe.  Both "install" and "SalarLogical/Integer"
> >potentially allocate memory, so at least one needs to be protected before
> >callling lang3.  (Passing one such argument would be OK, since lang3
> >protects its arguments, but it doesn't get a chance to do that while they
> >are still being evaluated.)
> 
> How true but who can blame him? The Writing R Extensions manual
> contains the same mistake:
> 
>   SEXP mkans(double x)
>   {
>     SEXP ans;
>     ans = PROTECT(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];
>   }

A further comment on this...  Currently, symbols are never garbage
collected, so you might think the above is OK, since the result
of install("x") can't be lost wen mkans(x) is called.  However, I
think it's not a good idea to rely on symbols never being collected.
In any case, though, even if you are relying on that, the code isn't
safe because C doesn't specify the order of evaluation of argments,
so mkans(x) might be called before install("x").

One should also note that the PROTECT within mkans is unnecessary,
and must surely be confusing to anyone who thought (correctly) 
that they had understood what PROTECT is for.

   Radford Neal



[Rd] Need help on calling Head from C
Radford Neal