From mtmorgan at fhcrc.org  Sat Jun 27 01:09:53 2009
From: mtmorgan at fhcrc.org (Martin Morgan)
Date: Fri, 26 Jun 2009 16:09:53 -0700
Subject: [Rd] bug in Rf_PrintValue ?
In-Reply-To: <c2350ba40906261201o2b2224a8w3e641686702fe40a@mail.gmail.com>
References: <c2350ba40906261201o2b2224a8w3e641686702fe40a@mail.gmail.com>
Message-ID: <4A455541.2000102@fhcrc.org>

Kynn Jones wrote:
> I'm very green with R, so maybe this is not a bug, but it looks like one to
> me.  The following program segfaults at the second call to Rf_PrintValue().
>  To failure depends on the value of the y-string.  E.g., if I change it from
> "coverage" to, say, "COVERAGE", the segfault does not occur.
> 
> /* bug.c */
> #include <stdio.h>
> #include <Rinternals.h>
> #include <Rembedded.h>
> 
> int main(int argc, char **argv) {
>   char *x = "foo";
>   char *y = "coverage";
>   SEXP x_r, y_r;
> 
>   Rf_initEmbeddedR(argc, argv);
>   PROTECT( x_r = mkChar( x ) );

mkChar creates a CHARSXP. These are not normally user-visible, but
instead are placed into a STRSXP (vector type of 'character' in R). So
you want to

    PROTECT( x_r = allocVector(STRSXP, 1) );
    SET_STRING_ELT(x_r, 0, mkChar( x ));

(There is also mkString( x ) for the special case of constructing
character(1)).

I think the segfault is because the CHARSXP returned by mkChar is
initialized with information different from that expected of
user-visible SEXPs (I think it is the information on chaining the node
to the hash table; see Defn.h:120 and memory.c:2844); I think the
success of Rf_PrintValue on 'foo' is a ghost left over from when
CHARSXPs were user-visible.

Martin

>   Rf_PrintValue( x_r );
>   printf( "OK\n" );
> 
>   PROTECT( y_r = mkChar( y ) );
>   Rf_PrintValue( y_r );
>   printf( "OK\n" );
> 
>   UNPROTECT( 2 );
>   return 0;
> }
> 
> I compile this code with:
> 
> % env -i PATH=/bin:/usr/bin ./myR/bin/R CMD LINK gcc -g
> -I./R-2.9.0/src/include -L./myR/lib64/R/lib -lR -lRblas bug.c -o bug
> 
> A run looks like this:
> 
> % env -i PATH=/bin:/usr/bin R_HOME=$(./myR/bin/R RHOME) ./bug -q --vanilla
> <CHARSXP: "foo">
> OK
> <CHARSXP: "coverage">
> 
>  *** caught segfault ***
> address 0x6c6c756e2e8d, cause 'memory not mapped'
> 
> Possible actions:
> 1: abort (with core dump, if enabled)
> 2: normal R exit
> 3: exit R without saving workspace
> 4: exit R saving workspace
> Selection: 1
> aborting ...
> zsh: segmentation fault  env -i PATH=/bin:/usr/bin R_HOME=$(./myR/bin/R
> RHOME) ./bug -q --vanilla
> 
> 
> I think the problem has to do with the fact that there may already exist a
> cached copy of "coverage" .
> 
> Regards,
> 
> Kynn
> 
> PS: Any comments on my code would be very welcome; I'm very much the noob
> with all this.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] bug in Rf_PrintValue ?
Martin Morgan