[R] calling stats::optim from Rcpp causes memory leak

Frantisek Bartos |@b@rto@96 @end|ng |rom gm@||@com
Fri Oct 16 00:34:10 CEST 2020

Hi, in part of my code I need to optimize a function from within Rcpp (I
followed the 2nd answer here
However, I found that the function leaks memory (very little, but it
compounds if it's a part of repeatedly running simulation). I created a
minimal reproducible example, but I have no idea where does the leak
originate. Could I ask for guidance on dealing with this issue?

Rcpp code:
#include <Rcpp.h>
using namespace Rcpp;
double objective_function(double x){
  double obj = .666 - x;
  return pow(obj, 2);
// [[Rcpp::export(leak)]]
double leak(double a, double b){

  // Extract R's optim function
  Rcpp::Environment stats("package:stats");
  Rcpp::Function optim = stats["optim"];

  // Call the optim function from R in C++
  Rcpp::List opt_results = optim(Rcpp::_["par"]    = .5,
                                 Rcpp::_["fn"]     =
                                 Rcpp::_["method"] = "Brent",
                                 Rcpp::_["lower"]  = a,
                                 Rcpp::_["upper"]  = b);

  // Extract out the estimated parameter values
  double mu = opt_results[0];

  // Return estimated values
  return mu;

R code:
  leak(0, 1)

When I look at my task manager, the MB usage under Rstudio R Session is
steadily increasing (which doesn't happen if I use any other function that
just returns a value).

Frantisek Bartos

	[[alternative HTML version deleted]]

More information about the R-help mailing list