View bounds checking

View’s docstring:

view(A, inds…)
Like getindex, but returns a view into the parent array A with the given indices instead of making a copy. Calling getindex or setindex! on the returned SubArray computes the indices to the parent array on the fly without checking bounds.

However, bounds are checked in practice:

view([1,2,3], 1:2)[3]   # triggers an error

Am I reading it right? It seems inconsistent.

You did a OOB access on the index not the array. The kind of undefined behavior described by the doc (and should never be used in real code) is

julia> idx = [1, 2]
2-element Array{Int64,1}:
 1
 2

julia> subary = view([1, 2, 3], idx)
2-element SubArray{Int64,1,Array{Int64,1},Tuple{Array{Int64,1}},false}:
 1
 2

julia> subary[2]
2

julia> idx[2] = 3
3

julia> subary[2]
3

julia> idx[2] = 4
4

julia> subary[2]
10

That makes sense. view([1, 2, 3], [1,4]) triggers an error, so it seems that the main issue is modifying the index array afterwards.

That warning could probably be worded a bit better. I believe it was originally written with the meaning that @cstjean first understood, but it’s ambiguous since there are two places where bounds checks can occur. Prior to 0.5, SubArrays themselves didn’t check bounds on indexing, but the parent array would still check bounds on the computed access.

In 0.5, that has now flipped. Views now check bounds upon indexing to ensure that accesses are within their size, but then they access the parent array with bounds checks turned off.

1 Like