Skip to content

Commit 6164598

Browse files
Improve documentation for inbounds macro (#42521)
* Warn that `@inbounds` is dangerous Seeing that the example usage in the documentation used to expose unsafe memory access (and I believe still does in the stable version) makes me think this warning is necessary. Co-authored-by: Tim Holy <[email protected]>
1 parent a0504ab commit 6164598

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

doc/src/devdocs/boundscheck.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,36 @@ your function contains multiple layers of inlining, only `@boundscheck` blocks a
3636
of inlining deeper are eliminated. The rule prevents unintended changes in program behavior from
3737
code further up the stack.
3838

39+
### Caution!
40+
41+
It is easy to accidentally expose unsafe operations with `@inbounds`. You might be tempted
42+
to write the above example as
43+
44+
```julia
45+
function sum(A::AbstractArray)
46+
r = zero(eltype(A))
47+
for i in 1:length(A)
48+
@inbounds r += A[i]
49+
end
50+
return r
51+
end
52+
```
53+
54+
Which quietly assumes 1-based indexing and therefore exposes unsafe memory access when used
55+
with [`OffsetArrays`](@ref man-custom-indice):
56+
57+
```julia
58+
julia> using OffsetArrays
59+
julia> sum(OffsetArray([1,2,3], -10))
60+
9164911648 # inconsistent results or segfault
61+
```
62+
63+
While the original source of the error here is `1:length(A)`, the use of `@inbounds`
64+
increases the consequences from a bounds error to a less easily caught and debugged unsafe
65+
memory access. It is often difficult or impossible to prove that a method which uses
66+
`@inbounds` is safe, so one must weigh the benefits of performance improvements against the
67+
risk of segfaults and silent misbehavior, especially in public facing APIs.
68+
3969
## Propagating inbounds
4070

4171
There may be certain scenarios where for code-organization reasons you want more than one layer

0 commit comments

Comments
 (0)