NumericMatrix:为什么我可以在没有错误的情况下超出其维度进行索引?

时间:2016-09-26 19:02:29

标签: r rcpp

我有R代码,它将matrix()对象传递给一个参数为NumericMatrix的Rcpp函数。 C ++函数给出了正确的尺寸,但我也可以将NumericMatrix索引超出其尺寸而不会出错。为什么会这样?下面的MWE(在RStudio中创建一个.cpp文件)后跟我看到的输出的一个实例,其中第三行显然是(?)从数组范围之外的内存中读取。

#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void myFn(Rcpp::NumericMatrix X) {
   std::cout << X.nrow() << std::endl;
   std::cout << X.ncol() << std::endl;

   std::cout << X(100,4) << std::endl;
}

/*** R
# create a matrix to be passed to the C++ function
mat = matrix(3, nrow=10, ncol=3)
myFn(mat)
*/

# 10
# 3
# 3.96421e+252

1 个答案:

答案 0 :(得分:4)

快速的几个:

  1. 您的代码包含RcppArmadillo标头并设置依赖,但不使用RcppArmadillo。不好的做法(虽然没有害处)。

  2. 你使用std::cout CRAN和WRE都皱眉头。

  3. 如果需要边界控制,请使用.at(i,j)访问器;出于性能原因,这是默认关闭。

  4. 下面的修改示例。

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    void myFn(Rcpp::NumericMatrix X) {
      Rcout << X.nrow() << " " << X.ncol() << std::endl;
      Rcout << X.at(100,4) << std::endl;
    }
    
    /*** R
    # create a matrix to be passed to the C++ function
    mat = matrix(3, nrow=10, ncol=3)
    myFn(mat)
    */
    

    如果你跑了,你会得到你想要的错误:

    R> Rcpp::sourceCpp("/tmp/indexExample.cpp")
    
    R> # create a matrix to be passed to the C++ function
    R> mat = matrix(3, nrow=10, ncol=3)
    
    R> myFn(mat)
    10 3
    Error in eval(substitute(expr), envir, enclos) (from srcConn#3) : index out of bounds
    R>