[Rcpp-devel] Interfacing Rcpp with a C library: memory allocation

Krzysztof Sakrejda krzysztof.sakrejda at gmail.com
Wed Nov 20 18:34:40 CET 2013


Without seeing your code, this is a lot like playing 20 questions, but
if your C code is correct, you
might get memory-related segfaults by misunderstanding the lifetime of
the R objects Rcpp references.

Krzysztof

On Wed, Nov 20, 2013 at 12:27 PM, Alessandro Mammana
<mammana at molgen.mpg.de> wrote:
> Dear all,
> I'm trying to write some efficient code for analyzing sequencing data
> in R. To do this I would like to use the C library samtools. I've
> created a package where the src directory looks like this:
>
> src
> |-- Makevars
> |-- RcppExports.cpp
> |-- mysourcecode.cpp
> `-- samtools
>     |-- all *.c and *.h files as well as an independent Makefile
>
> My Makevars file looks like this:
>
> PKG_CPPFLAGS = -Isamtools
> PKG_LIBS = `$(R_HOME)/bin/Rscript -e "Rcpp:::LdFlags()"`
> PKG_LIBS += -Lsamtools  -lbam -lz -lpthread
>
> $(SHLIB): samtools/libbam.a
>
> samtools/libbam.a:
>       @(cd samtools-0.1.19 && $(MAKE) libbam.a \
>           CC="$(CC)" CFLAGS="$(CFLAGS) $(CPICFLAGS)" AR="$(AR)"
> RANLIB="$(RANLIB)")
>
> Everything compiles and I get my cpp functions in R, however I am
> getting some weird segfaults, I think they are due to memory
> allocation, but it's hard for me to track them. Especially now, these
> errors are showing up not immediately, but at the second time that I
> call a Rcpp function.
>
> I wanted to ask the following:
> 1. Is it the right way of using external C libraries? I couldn't find
> much documentation around
> 2. The C library uses malloc and free, and so do I (as little as
> possible, just to interface with the library), is this mechanism
> clashing against Rcpp/R memory management? Could it happen, for
> instance, that R tries to free allocated memory that I already
> manually freed myself?
>
> In general I didn't understand much about memory allocation in Rcpp
> and I couldn't find many resources talking about it. Is there anything
> R- or Rcpp-specific that I have to keep in mind or should I program as
> if I were programming in C/C++?
>
> Thanks a lot!
>
>
> --
> Alessandro Mammana, PhD Student
> Max Planck Institute for Molecular Genetics
> Ihnestraße 63-73
> D-14195 Berlin, Germany
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel



-- 

Krzysztof Sakrejda

Organismic and Evolutionary Biology
University of Massachusetts, Amherst
319 Morrill Science Center South
611 N. Pleasant Street
Amherst, MA 01003

work #: 413-325-6555
email: sakrejda at cns.umass.edu
-----------------------------------------------


More information about the Rcpp-devel mailing list