Rcpp功能崩溃

pfi*_*fas 9 r rcpp

我的问题:

我在64位Windows7 PC上使用R.3.0.1和RStudio 0.97.551,我已经开始使用Rcpp将函数外包给C/C++.该函数编译,但在R函数内对其进行评估会产生运行时错误.我无法找出原因以及如何解决这个问题.

细节

下面是我的cpp文件...让我们说它叫做"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(a-b-c);
}
Run Code Online (Sandbox Code Playgroud)

我使用该命令在R(或RStudio)中编译

sourceCpp(<path to file>/vector.cpp)
Run Code Online (Sandbox Code Playgroud)

它汇编 - 到目前为止一切顺利.但是,当我继续在其他R函数中使用函数l5时,它经常导致R崩溃(在RStudio和普通R GUI中).事实上,评估它本身并不是更稳定.为了重现这一点,例如尝试多次评估l6

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)
}
Run Code Online (Sandbox Code Playgroud)

并运行

l6(0.9, 0.1, 67, 40, 0.5, 44, 1.06)
Run Code Online (Sandbox Code Playgroud)

具体来说,它会产生以下运行时错误

This application has requested Runtime to terminate it in an unusual way. 
Run Code Online (Sandbox Code Playgroud)

那我的功能有什么问题?

正如Dirk在下面提出的那样,在for循环中存在一个基本错误,其中我从0到n运行,因此有n + 1个元素,但我只初始化了长度为n的向量.为了避免这个错误,我现在使用迭代器实现了这个函数

#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(a-b-c);
}
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Dir*_*tel 11

你正在犯一个基本的C/C++错误:

for(int i=0; i<n+1; i++)
Run Code Online (Sandbox Code Playgroud)

将被访问n+1次数,但您分配了n空格.