Skip to content

Commit

Permalink
SA5011: don't flag indexing of possibly nil slice
Browse files Browse the repository at this point in the history
Indexing a nil slice doesn't cause a nil pointer dereference, "only"
an out of bounds.

This fix also acts as a workaround for gh-1051 and gh-1053.

Closes gh-1051
Updates gh-1053

(cherry picked from commit 4e580ec)
  • Loading branch information
dominikh committed Aug 16, 2021
1 parent fae7339 commit f3761a6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions staticcheck/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -4099,6 +4099,13 @@ func CheckMaybeNil(pass *analysis.Pass) (interface{}, error) {
ptr = instr.Addr
case *ir.IndexAddr:
ptr = instr.X
if _, ok := ptr.Type().Underlying().(*types.Slice); ok {
// indexing a nil slice does not cause a nil pointer panic
//
// Note: This also works around the bad lowering of range loops over slices
// (https://github.com/dominikh/go-tools/issues/1053)
continue
}
case *ir.FieldAddr:
ptr = instr.X
}
Expand Down
33 changes: 33 additions & 0 deletions staticcheck/testdata/src/CheckMaybeNil/CheckMaybeNil.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,36 @@ func fn15(x *int) {
assert(x != nil)
_ = *x
}

func fn16() {
var xs []int
if xs == nil {
println()
}

for _, x := range xs {
_ = x
}

var xs2 *[1]int
if xs2 == nil {
println()
}
for _, x := range xs2 { // want `possible nil pointer dereference`
_ = x
}

var xs3 *[]int
if xs3 == nil {
println()
}
for _, x := range *xs3 { // want `possible nil pointer dereference`
_ = x
}

var xs4 []int
if xs4 == nil {
println()
}
_ = xs4[0]
}

0 comments on commit f3761a6

Please sign in to comment.