Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 这场恐慌的原因是什么?_Go_Segmentation Fault - Fatal编程技术网

Go 这场恐慌的原因是什么?

Go 这场恐慌的原因是什么?,go,segmentation-fault,Go,Segmentation Fault,为了练习一些基本概念,我正在编写一个简单的端口扫描仪。然而,当尝试实现goroutines时,程序陷入恐慌,我遇到了一个分段错误: Scanning ports {Port:139 State:Open} {Port:135 State:Open} {Port:136 State:Closed} {Port:131 State:Closed} {Port:131 State:Open} {Port:134 State:Closed} {Port:134 State:Open} panic: ru

为了练习一些基本概念,我正在编写一个简单的端口扫描仪。然而,当尝试实现goroutines时,程序陷入恐慌,我遇到了一个分段错误:

Scanning ports
{Port:139 State:Open}
{Port:135 State:Open}
{Port:136 State:Closed}
{Port:131 State:Closed}
{Port:131 State:Open}
{Port:134 State:Closed}
{Port:134 State:Open}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]

goroutine 20 [running]:
main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x83)
        /home/athos/Projects/go-tutorial/scanner.go:33 +0x1ea
created by main.main
        /home/athos/Projects/go-tutorial/scanner.go:41 +0xf1
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4eb26a]

goroutine 23 [running]:
main.scanPort(0x52033b, 0x3, 0x52203e, 0xf, 0x86)
        /home/athos/Projects/go-tutorial/scanner.go:33 +0x1ea
created by main.main
        /home/athos/Projects/go-tutorial/scanner.go:41 +0xf1
exit status 2
这是我的代码:

包干管 进口 fmt 网 strconv 同步 时间 var wg sync.WaitGroup 类型scanResult结构{ 端口int 状态字符串 } func scanPortprotocol,主机名字符串,端口int{ 延迟工作组完成 结果:=scanResult{Port:Port} 套接字:=主机名+:+strconv.Itoaport 连接,错误:=net.DialTimeoutprotocol,套接字,2*time.Second 如果错误!=零{ 结果。状态=关闭 fmt.Printf%+v\n,结果 } 结果。状态=打开 fmt.Printf%+v\n,结果 //延迟:FILO数据结构 延迟连接关闭 } func main{ fmt.println扫描端口 对于i:=130;inet.DialTimeout返回一个连接和一个错误,您可以正确地检查错误是否为零,但即使有错误,您也可以打印它并继续

如果存在非零错误,则不应使用返回的连接,因为该连接可能为零或无效值。如果存在错误,请检查/打印并返回,不要尝试使用conn

因此,简单地返回:

if err != nil {
    result.State = "Closed"
    fmt.Printf("%+v\n", result)
    return
}
此外,如果没有错误,您可以计划立即、延迟关闭连接。如果您在函数中最后一件事关闭连接,则使用延迟没有意义

所以应该是这样的:

conn, err := net.DialTimeout(protocol, socket, 2*time.Second)

if err != nil {
    result.State = "Closed"
    fmt.Printf("%+v\n", result)
    return
}

defer conn.Close()

result.State = "Open"
fmt.Printf("%+v\n", result)

可能在处理错误时添加return?因为,如果发生错误,conn可能为nil。从计算行号来看,当conn为nil时,似乎调用了conn.Close。完成了!谢谢。