Rcpp function failed

My problem:

I use R.3.0.1 along with RStudio 0.97.551 on a 64-bit PC with Windows7, and I started to transfer functions in C / C ++ using Rcpp. The function compiles, but evaluating it inside the R function creates a runtime error. I can’t find out why and how to fix it.

More details

Below is my cpp file ... let it be called "vector.cpp"

#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector l5(double z, double k, double s, double K, double theta, double x, double h, NumericVector m){ int n = m.size(); NumericVector a(n); NumericVector bu(n); NumericVector b(n); NumericVector c(n); for(int i=0; i<n+1; i++){ a[i] = pow(z,m[i]) * (pow((x*pow(h,m[i])/K), theta) - 1) * (K/theta); for (int j=0; j<i; j++){ bu[i] += pow(z,j) * (1 - z) * fmax(((pow((s/K), theta) - 1) * (K/theta)), ((pow((x*pow(h, j)/K), theta) - 1) * (K/theta))); } b[i] = k *bu[i]; c[i] = k * pow(z, m[i]) * fmax(((pow((s/K), theta) - 1) * (K/theta)), ((pow((x*pow(h, m[i])/K), theta) - 1) * (K/theta))); } return wrap(abc); } 

which I compile in R (or RStudio) with the command

 sourceCpp(<path to file>/vector.cpp) 

It compiles - so far so good. However, when I continue to use the l5 function in other R functions, it often causes R to crash (in both RStudio and the regular R GUI). In fact, the assessment itself is not more stable. To reproduce this, for example, try evaluating l6 several times

 l6 <- function(zs, ks, ss, Ks, thetas, xs, hs){ z=zs k=ks s=ss K=Ks theta=thetas x=xs h=hs m=0:30 res <- l5(z, k, s, K, theta,x, h, m) return(res) } 

and run

 l6(0.9, 0.1, 67, 40, 0.5, 44, 1.06) 

In particular, it creates the following runtime error

 This application has requested Runtime to terminate it in an unusual way. 

So what is wrong with my function?

Decision

As Dirk suggested below, there is an elementary error in the for loop where I runs from 0 to n and therefore has n + 1 elements, but I only initialized vectors of length n. To avoid this error, I now implemented a function using iterators

 #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector l5(double z, double k, double s, double K, double theta, double x, double h, NumericVector m){ int n = m.size(); NumericVector a(n); NumericVector bu(n); NumericVector b(n); NumericVector c(n); for(NumericVector::iterator i = m.begin(); i != m.end(); ++i){ a[*i] = pow(z, m[*i]) * (pow((x*pow(h, m[*i])/K), theta) - 1) * (K/theta); for(int j=0; j<*i; j++){ bu[*i] += pow(z,j) * (1 - z) * fmax(((pow((s/K), theta) - 1) * (K/theta)), ((pow((x*pow(h, j)/K), theta) - 1) * (K/theta))); } b[*i] = k *bu[*i]; c[*i] = k * pow(z, m[*i]) * fmax(((pow((s/K), theta) - 1) * (K/theta)), ((pow((x*pow(h, m[*i])/K), theta) - 1) * (K/theta))); } return wrap(abc); } 

Thanks again!

+8
r rcpp
source share
1 answer

You make a basic C / C ++ error:

 for(int i=0; i<n+1; i++) 

time n+1 will be available, but you have selected spaces n .

+8
source share

All Articles