Modifying view index results in silent out-of-bound access

The view doc says

The behavior is undefined if the shape of the parent array is changed after view is called
because there is no bound check for the parent array; e.g., it may cause a
segmentation fault.

but it doesn’t mention what will happen if I change the index (rather than the parent array).

julia> ind = [1]
1-element Vector{Int64}:
 1

julia> vals = [10]
1-element Vector{Int64}:
 10

julia> v = view(vals, ind)
1-element view(::Vector{Int64}, [1]) with eltype Int64:
 10

julia> ind[1] = 2
2

julia> v[1]
0

What happened here? Is this undefined behavior?

It’s undefined behavior. view does a bounds check on the indices when the view (SubArray) is constructed, but thereafter it assumes that the indices don’t change and hence it assumes @inbounds is correct — apparently it reads past the end of the array in this example.

Probably the documentation should have a warning about mutating the indices after a view is constructed. Or possibly the @inbounds should be removed here (to be replaced with @propagate_inbounds so that the caller can still eliminate the bounds check).

2 Likes