Skip to content
Prev 67615 / 398506 Next

terminate R program when trying to access out-of-bounds array element?

One way could be to make a special class with an indexing method that 
checks for out-of-bounds numeric indices.  Here's an example for vectors:

 > setOldClass(c("oobcvec"))
 > x <- 1:3
 > class(x) <- "oobcvec"
 > x
[1] 1 2 3
attr(,"class")
[1] "oobcvec"
 > "[.oobcvec" <- function(x, ..., drop=T) {
+    if (!missing(..1) && is.numeric(..1) && any(is.na(..1) | ..1 < 1 | 
..1 > length(x)))
+        stop("numeric vector out of range")
+    NextMethod("[")
+ }
 > x[2:3]
[1] 2 3
 > x[2:4]
Error in "[.oobcvec"(x, 2:4) : numeric vector out of range
 >

Then, for vectors for which you want out-of-bounds checks done when they 
indexed, set the class to "oobcvec".  This should work for simple 
vectors (I checked, and it works if the vectors have names).

If you want this write a method like this for indexing matrices, you can 
use ..1 and ..2 to refer to the i and j indices.  If you want to also be 
able to check for missing character indices, you'll just need to add 
more code.  Note that the above example disallows 0 and negative 
indices, which may or may not be what you want.

If you're extensively using other classes that you've defined, and you 
want out-of-bounds checking for them, then you need to integrate the 
checks into the subsetting methods for those classes -- you can't just 
use the above approach.

hope this helps,

Tony Plate
Vivek Rao wrote: