doupang5433 2016-10-23 08:58
浏览 96
已采纳

意外的无效内存地址或nil指针取消引用

I'm getting a runtime error for an invalid memory address.

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x4e0f24]

goroutine 1192592 [running]:
panic(0x793540, 0xc420010040)
#011/usr/local/go/src/runtime/panic.go:500 +0x1a1
foobar/sd.(*Channel).Attributes(0x0, 0xc420110101, 0xc42278f9b0, 0x9)
#011/home/app/go/src/foobar/sd/channel.go:36 +0x54

channel.go looks like this:

35 func (m *Channel) Attributes() (*ChannelAttrs, error) {
36    redisHash := "sd:channels:" + m.hash
37
38    rc := m.ctx.RedisPool.Get()
39    values, err := redis.Values(rc.Do("HGETALL", redisHash))
40    rc.Close()
41    if err != nil {
42        return nil, err
43    }
44    attrs := ChannelAttrs{}
45    redis.ScanStruct(values, &attrs)
46    return &attrs, nil
47 }

How is it possible that the line 36 is causing this? Is it somehow possible for m to be nil? If so, how?

Note: hash is defined as string

  • 写回答

1条回答 默认 最新

  • dongxuan1314 2016-10-23 09:08
    关注

    This means that Attributes is being called with receiver m as nil.

    In principle methods can be called with nil receivers (and this may even be useful if they check for nil) - see here - but this particular method Attributes() is not designed to be called with a nil receiver, as m is being dereferenced without a nil check. This (method being called with a nil receiver m) is what is happening in your calling code.

    See a simplified example on the playground here, and note that commenting out + m.hash makes the whole thing work fine, as here.

    Code below:

    package main
    
    import (
        "fmt"
    )
    
    type Channel struct {
        hash string
    }
    
    func (m *Channel) Attributes() {
        r := "x" + m.hash
        fmt.Println(r)
    }
    
    func main() {
        var c *Channel
        c.Attributes()
    }
    

    The output of which is:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x20131]
    
    goroutine 1 [running]:
    panic(0x102360, 0x1040a038)
        /usr/local/go/src/runtime/panic.go:500 +0x720
    main.(*Channel).Attributes(0x0, 0x104000f0)
    /tmp/sandbox285779060/main.go:12 +0x131
    main.main()
        /tmp/sandbox285779060/main.go:18 +0x20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况