c++ - RStudio 与 Rcpp 一起不断崩溃

标签 c++ r rcpp

我想了解是什么导致该程序崩溃。我至少看到了三个相关问题here , herehere ,但我还没有找到解决该问题的明确答案,因此这里有一些示例代码来复制该问题。

R 代码:

library(Rcpp)

Rcpp::sourceCpp("myfunction.cpp")

data1      <- rnorm(2000)
data2      <- rnorm(2000)

mydata <- matrix(cbind(data1, data2), nrow=2000, ncol=2)
values <- log(1:6)

for (i in 1:1000) {
  myfunction(values, mydata)
}

C++ 代码:

#include "Rcpp.h"
#include "math.h"
using namespace Rcpp;

// [[Rcpp::export]]
double myfunction(const NumericVector& theta, const NumericMatrix& data) {

  double ans = 0;

  int theta_size = theta.length();
  NumericVector mytheta(theta_size);

  int data_size = data.nrow();
  NumericMatrix mat(data_size, 2);

  for (int i = 0; i < theta_size; i++) {
    mytheta(i) = exp(theta(i));
  }

  if ( true ) {  // Flow control

    for (int i = 0; i < data_size; i++) {
      mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1);
      ans = ans + 1;
    }

    for (int i = 0; i < data_size; i++) {
      mat(i, 2) = pow(data(i-1, 2), 2) + mytheta(4)*mat(i-1, 2);
      ans = ans + 1;
    }

  }

  Rcout << "Ok!\n";

  return ans;
}

一切工作正常至少第一次我使用myfunction(),但在 R for 循环中调用时它崩溃了。我重新安装了 R、Rtools 和 RStudio(在 Windows 上)以查看安装是否有问题,但我仍然面临同样的问题。

这使得 R 和 C++ 之间的无缝集成变得不像我最初想象的那样无缝,而且由于我发现我不是唯一面临这个问题的人,看起来我们都在做一些从 Rcpp 开始时(至少在 RStudio 上)明显的错误,但它是什么?

本质上,我想确保我没有错过这里完全明显的东西,因为到目前为止我看到的所有答案似乎都暗示情况确实如此。

注意:这是我使用 Rcpp 测试的较长函数的缩短版本,原始版本在我调用它的前几次次中似乎工作正常,但它最终也会崩溃。

更新:删除了 rm(),哎呀。

最佳答案

for (int i = 0; i < data_size; i++) {
  mat(i, 1) = pow(data(i-1, 1), 2) + mytheta(1)*mat(i-1, 1);
  ans = ans + 1;
}

i == 0时,您尝试访问data(-1, 1),事情从那里开始变成梨形。事实上,你第一次运行它时它没有崩溃,这仅仅意味着你很幸运(或者不幸,因为它引诱你产生了错误的自信感)。

关于c++ - RStudio 与 Rcpp 一起不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50143425/

相关文章:

r - 在 R/Rcpp 中转置列表的最快方法

c++ - 使用 boost C++ 创建 Json 数组

c++ - std::sort 自定义比较器

r - 使用两种方法调用 ggplot() 时出现美学错误

r - 计算 NA 之间的行数

c++ - 带有 RcppArmadillo 的 R 包中的 ARMA_NO_DEBUG

C++ 转换模板

c++ - Crypto++ 无法构建 Qt 应用程序

如果 R 中的 n Obs < x,则删除重复的 obs 数据

r - cxxfunction中的多个插件