From radford at cs.toronto.edu  Sat Jun 28 00:32:22 2014
From: radford at cs.toronto.edu (Radford Neal)
Date: Fri, 27 Jun 2014 18:32:22 -0400
Subject: [Rd] Need help on calling Head from C
In-Reply-To: <53ADB11F.1050004@fhcrc.org>
References: <20140626203624.GA17415@cs.toronto.edu>
	<53AC997E.2070706@fhcrc.org>
	<20140627092348.GA23738@cs.toronto.edu>
	<53ADB11F.1050004@fhcrc.org>
Message-ID: <20140627223222.GA8338@cs.toronto.edu>

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

> >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.
> 
> 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.

There's certainly something to be said in favour of the "better safe
than sorry" approach to using PROTECT.  But in the context of a tutorial,
one shouldn't put one in that's unnecessary without a comment saying,
"not needed at the moment, but would be if code that allocates more
memory is added later, so let's be safe and do it now too".  Otherwise,
the reader may infer an incorrect model of when to PROTECT, such as 
"you should PROTECT every allocated object, then UNPROTECT at the end of
the procedure - do that and you'll be OK".  Of course, that's not
enough to be OK.  And to illustrate the correct model, one needs some
negative examples as well as positive examples.

   Radford Neal



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