calling stats::optim from Rcpp causes memory leak

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

calling stats::optim from Rcpp causes memory leak

Frantisek Bartos
Hi, in part of my code I need to optimize a function from within Rcpp (I
followed the 2nd answer here
https://stackoverflow.com/questions/48348079/applying-the-optim-function-in-r-in-c-with-rcpp).
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::InternalFunction(&objective_function),
                                 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:
repeat{
  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).

Thanks,
Frantisek Bartos

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.