Skip to content
Prev 48553 / 63424 Next

Need help on calling Head from C

On 06/27/2014 02:23 AM, Radford Neal wrote:
I understand what PROTECT is for and I don't find the PROTECT in mkans
confusing.

Maybe it's not necessary now. But it's so much simpler/safer to just
systematically protect any freshly allocated SEXP. One day
someone might need to modify mkans(), say, add a call to warning() or
Rprintf() after the call to allocVector(), and will most likely forget
to add the PROTECT/UNPROTECT that will then become necessary. So at
least there should be a comment next to the allocVector() call in
mkans() to explain why in this particular case the returned value
doesn't need to be protected (but writing the comment probably takes
as much time as doing the PROTECT/UNPROTECT anyway).

Even now, why should I rely on the fact that the REAL() macro doesn't
allocate memory and will never do so?

So with systematic protection:

      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)
      {
          SEXP symbol, value;
          PROTECT(symbol = install("x"));
          PROTECT(value = mkans(x));
          defineVar(symbol, value, rho);
          UNPROTECT(2);
          return(REAL(eval(f, rho))[0]);
      }

I doubt you'll ever be able to detect any difference in terms of speed
or memory usage because the cost of PROTECT/UNPROTECT is virtually 0.
Furthermore, one could imagine a static code checker would be able to
verify this and warn me about missing PROTECTs.

BTW I appreciate the work you're doing on pqR and hopefully more of the
stuff you've done will get merged into R at some point.

Cheers,
H.