[Rcpp-devel] Best way to return raw array

Dirk Eddelbuettel edd at debian.org
Fri Sep 2 03:34:31 CEST 2011

On 2 September 2011 at 10:16, Darren Cook wrote:
| I've extended Christian Gunning's speed test with an STL and C/C++
| version; I was about to post but then I got a bit stuck with using
| Rcpp::wrap() for a raw block of memory. I'm using this:
| src1cpp<-'
| int nn=as<int>(n);
| double *p=new double[nn];
| ...
| NumericVector ret(p,p+nn);
| delete p;
| return ret;
| '

That strikes me as plain wrong code. 

a) Do not use new / delete on memory shared with R; see Writing R Extensions
for details. There are Calloc etc if you must.

b) If you allocate memory AND then want to reuse it in a Rcpp vector you
cannot delete it, and you should have used R allocators in the first place as
per a).

c) The whole point of what we do with Rcpp is to NOT have to deal with new /
delete and or malloc / free.  Even if you think it's cool and know how to it
in plain, it is simply against the whole spirit we try to build where we
claim that Rcpp is newbie friendlier because you don't have to do pointers by
hand.  So please don't post it here.  STL idioms are really much better.


| mysample_cpp<-cxxfunction( signature(n="numeric"), src1cpp, plugin='Rcpp')
| At first I wasn't using "delete p", and it worked fine, but the memory
| leak bothered me. Now I've added the delete it (irregularly) gives bad
| results. E.g.
|  mysample_cpp(10)
|  [1]  1.00000e+01  1.00000e+01  1.00000e+01  1.00000e+01  1.00000e+01
| 1.00000e+01 6.74011e+199  1.00000e+01  1.00000e+01  1.00000e+01
| So,
|  Q1: Was there no memory leak? I.e. R has taken control of my memory
| block and will delete it for me?
|  Q2: Is this the best way to do it (with maximum speed, but no memory
| leaks, in mind)?
| Darren
| -- 
| Darren Cook, Software Researcher/Developer
| http://dcook.org/work/ (About me and my work)
| http://dcook.org/blogs.html (My blogs and articles)
| _______________________________________________
| 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

Two new Rcpp master classes for R and C++ integration scheduled for 
New York (Sep 24) and San Francisco (Oct 8), more details are at

More information about the Rcpp-devel mailing list