有没有一个可以找到“nil指针解引用”潜在恐慌的Go语言代码检查工具?

huangapple go评论83阅读模式
英文:

Is there a go linter that can find "nil pointer dereference" potential panic?

问题

这是一个简单的示例:

package main

import "fmt"

type A struct {
    Name *string
}

type B struct {
    A *A
}

func main() {
    deref(&B{})
}

func deref(b *B) {
    fmt.Println(*b.A.Name) // panic: nil pointer dereference
}

我正在寻找一种可以找到这种情况的解决方案。Jetbrains Goland 中有一个 "nillness check",但它不会检查这个问题。

英文:

Here is simple example:

package main

import "fmt"

type A struct {
	Name *string
}

type B struct {
	A *A
}

func main() {
	deref(&B{})
}

func deref(b *B) {
	fmt.Println(*b.A.Name) // panic: nil pointer dereference
}

I'm looking for a solution that can find this type of situations.
There is a "nillness check" in Jetbrains Goland but it doesn't inspect this issue.

答案1

得分: 6

我在其他地方问了你的问题[1],并得到了以下回答:

> 检测所有的nil指针解引用是不可能的,因为会产生误报,而我们通常不容忍误报。而且计算起来也相当昂贵。
>
> 检测这种简单的nil指针解引用并不值得,因为即使对代码进行微小的修改,它们也不再容易检测到。
>
> 我们确实有SA5011,它可以标记一种特定类型的潜在nil指针解引用,但这对你的示例没有帮助。

  1. https://github.com/dominikh/go-tools/issues/1035
英文:

I asked your question somewhere else [1], and got this response:

> Detecting all nil pointer dereferences is impossible without false positives,
> and we don't generally tolerate false positives. It would also be fairly
> expensive to compute.
>
> Detecting trivial nil pointer dereferences like this one isn't worth it,
> because even with minor additions to the code they would no longer be easy to
> detect.
>
> We do have SA5011 which flags a
> specific kind of potential nil pointer dereference, though this wouldn't help
> with your example.

  1. https://github.com/dominikh/go-tools/issues/1035

huangapple
  • 本文由 发表于 2021年6月13日 03:09:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/67952200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定