Question

I've got a mixed C [cblas] / C++ [library code] library (developed by someone else) that I have wrapped in Rcpp.

Many methods have code like the one below:

void myclass::calculate() {
    double* dataSums = (double*) calloc(N, sizeof(double));
    if(dataSums == NULL) { printf("Memory allocation failed!\n"); exit(1); }

    // do some calculations ...
    cblas_dgemm(...);
    free(dataSums); dataSums = NULL;
}

Of course, the exit(1) is a problem here: when called from R, it shuts R down as well, which is what I don't want.

What is the best way to make sure that:

  • R does not shut down when an error occurs (replace exit calls with exceptions?)
  • memory is properly cleaned up after
  • cblas stays as performant as possible (is it a problem to use std::vectors?)
  • minimal changes to the library so it's easier to update from upstream
Was it helpful?

Solution

I would suggest something like

if (dataSums == NULL)  Rcpp::stop("Memory allocation failed!\n"); 

You have the corresponding (C++) layer of try / catch wrapped around your code anyway if you use Rcpp attributes, or inline, or when you do it by hand following the examples we have provided over the years. And given the C++ exception layer, you can just use it.

If your code layer needs extra cleanup, you may add that layer there. But C++ data structures will be unwound properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top