[Rcpp-devel] Have I noticed memory management bug in RcppArmadillo or is this the intended behaviour?

Slava Razbash slava.razbash at gmail.com
Thu Oct 27 11:17:32 CEST 2011


Hello,

I noticed that a C++ function that I using RcppArmadillo and some R
API was increasing R's memory usage after exiting and and ecan after a
call to gc(). So I ran some "tests", which I will describe below,
along with my observations. My question are: (1) Am I observing the
intended behaivour of R/RcppArmadillo? (2)If the answer to (1) is
"no",  then is it a bug? How should I proceed?
I am using Windows 7-64bit, R 2.13.2 and Rtools 14 and using R in the terminal.


I ran the following in R:
for(i in 1:999999) { .Call("myFunction", myParameters) }


Observation:
1. Rterm's memory usage increases by an amount x.

Then I call:
gc()

Observation:
2. Rterm's memory usage decreases by an amount substantially less than x.


To check I had I programmed a memory leak into my code, I compiled the
example "fastLm" code from
http://dirk.eddelbuettel.com/code/rcpp.armadillo.html into a skeleton
package.

Then ran:
for(i in 1:999999) { .Call("fastLm", c(1:10), matrix(1,nrow=10, ncol=1)) }

My observations where the same as above.

I then ran the following:

for(i in 1:999999) { a <- 5 * 6 }

R's memory usage did increase. But a call to:
gc()
Brought it back to what it was before running for(i in 1:999999) { a <- 5 * 6 }

I then wrote a trivial C function with the R API. My function:

#include <R.h>
#include <Rinternals.h>

SEXP tester(SEXP number_s, SEXP vec_s) {
	double *number = REAL(number_s);
	double *vec = REAL(vec_s);
	
	SEXP res;
	
	PROTECT(res = allocVector(REALSXP, length(vec_s)));
	
	for(int i =0; i < length(res); i++) {
		REAL(res)[i] = *number * vec[i];
		
	}
	number = 0;
	vec = 0;
	UNPROTECT(1);
	return res;
}


I compiled it with R CMD SHLIB and loaded it with dyn.load().

I ran:
for(i in 1:999999) { .Call("tester", as.numeric(7), as.numeric(c(1:10)) ) }

The memory used by Rterm increased by an amount y.
But a call to:
gc()
Decreased the amount of memory used by y.

So in all of the above "tests", the only ones where gc() did not
decrease the amount of memory used by Rterm.exe by the same about as
the for() { myCode } increased it by were the ones where I used
RcppArmadillo.

What my function had in common with the fastLm functions is that both used:
return Rcpp::List::create( );
and both used arma::mat objects.

Thanks,

Slava


More information about the Rcpp-devel mailing list