From hpages at fhcrc.org  Fri Jun 27 00:06:54 2014
From: hpages at fhcrc.org (=?ISO-8859-1?Q?Herv=E9_Pag=E8s?=)
Date: Thu, 26 Jun 2014 15:06:54 -0700
Subject: [Rd] Need help on calling Head from C
In-Reply-To: <20140626203624.GA17415@cs.toronto.edu>
References: <20140626203624.GA17415@cs.toronto.edu>
Message-ID: <53AC997E.2070706@fhcrc.org>

Hi,

On 06/26/2014 01:36 PM, Radford Neal wrote:
>>> PROTECT(dfm=lang3(install("data.frame"),df,ScalarLogical(FALSE)));
>>> SET_TAG(CDDR(dfm), install("stringsAsFactors")) ;
>>> SEXP res = PROTECT(eval(dfm,R_GlobalEnv));
>>> PROTECT(head=lang3(install("head"),res,ScalarInteger(1)));
>>> head  = PROTECT(eval(head,R_GlobalEnv));
>>>
>>>
>>> I tried the above following , it seemed to be not working . Can you please
>>> help.
>>>
>>
>> Can you elaborate? The above code works AFAICT ...
>
> 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];
   }

Reported here more than 6 years ago and never fixed:

   https://stat.ethz.ch/pipermail/r-devel/2008-January/048040.html

Cheers,
H.

>
> Now, I'm not sure this is the source of the actual problem, since both
> "data.frame" and "head" presumably already exist, so the install won't
> actually allocate memory.  But this is not a safe coding method in
> general.
>
>     Radford Neal
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

-- 
Herv? Pag?s

Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
P.O. Box 19024
Seattle, WA 98109-1024

E-mail: hpages at fhcrc.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319



[Rd] Need help on calling Head from C
=?ISO-8859-1?Q?Herv=E9_Pag=E8s?=