Question

I am experimenting with Rcpp to see how boundary checking works:

> cppFunction ('double fun(){NumericVector v(5); return v[-10];}', rebuild=T)
> fun()
[1] 1.782105e-316
> cppFunction ('double fun(){NumericVector v(5); return v[5];}', rebuild=T)
> fun()
[1] 5.323385e-316

> cppFunction ('NumericVector fun(){NumericMatrix v(5, 5); return v(6,_);}', rebuild=T)
> fun()
Error: index out of bounds
> cppFunction ('double fun(){NumericMatrix v(5, 5); return v(6,1);}', rebuild=T)
> fun()
[1] 0

I can't really understand how it is (not) working. I was expecting 'index out of bounds' error for all 4 of them. What should I do to make it always work for both vectors and matrices? Here are some verbose output from compilation:

Generated R functions 
-------------------------------------------------------

`.sourceCpp_81484_DLLInfo` <- dyn.load('/tmp/RtmprtDNus/sourcecpp_5b065bfe9a2d/sourceCpp_20261.so')

fun <- Rcpp:::sourceCppFunction(function() {}, FALSE, `.sourceCpp_81484_DLLInfo`, 'sourceCpp_81484_fun')

rm(`.sourceCpp_81484_DLLInfo`)

Building shared library
--------------------------------------------------------

DIR: /tmp/RtmprtDNus/sourcecpp_5b065bfe9a2d

/usr/lib/R/bin/R CMD SHLIB -o 'sourceCpp_20261.so' --preclean 'file5b0652a2d520.cpp' 
g++ -I/usr/share/R/include -DNDEBUG    -I"/home/user/R/x86_64-pc-linux-gnu-library/3.0/Rcpp/include" -fpic  -O3 -pipe  -g  -c file5b0652a2d520.cpp -o file5b0652a2d520.o
g++ -shared -o sourceCpp_20261.so file5b0652a2d520.o -L/usr/lib/R/lib -lR

Do I need to modify -O3 or -DNDEBUG arguments?

Was it helpful?

Solution

For the two first examples, there are no bounds checks. Bounds checks are expensive. What you get is undefined behavior. Symptoms in this case are you get garbage, but you could also get a segfault.

Your third example use the _ placeholder to extract a row. Upon construction of the MatrixRow object, which represents the concept of the row, an exception is thrown because there is no such row. You can reason that it is worth here to do a bounds check since it checks "the whole row".

Your last example looks like a bug. probably in Vector::offset

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