dtd793353 2018-11-20 19:22
浏览 15

Golang中的无效内存地址

I have checked several other answers and they gave me some good thoughts on how to troubleshoot this but I still can't figure it out.

    localID := generateGenericID("local") // type int64
    localName := "local" // type string

    // set them to pointers as I need them as type *int64 and *string
    plocalID := &localID
    plocalName := &localName

    // create a pointer to a new github org
    var org *github.Organization

    // create a new general purpose org
    o := Org{}

    // Check for nil, per several other answers
    if plocalName != nil {
        o.Name = plocalName
        org.Login = plocalName // ERROR
    }

    if plocalID != nil {
        o.ID = plocalID
        org.ID = plocalID
    }

   fmt.Println(*plocalName) // prints local


    hunt.addOrganization(org) // takes a pointer to a github org
    report.addReportOrganization(&o) // take a pointer to an org

The error message I am getting is:

panic: runtime error: invalid memory address or nil pointer 

It points to the line marked ERROR. The error makes no sense due to me checking for nil, so I am wondering if maybe I am some kind of pointer hell due to creating a variable that is a pointer and then assigning pointers to it.

Should I simply create the github org as a normal struct and then pass in &org to the hunt function. I tried that and got past the error but a ton of other code pukes so before I start to chase this down I figured I would ask if that even makes sense of if I am looking in the wrong spot. RTFM with links is always welcome.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongtu9823 2018-11-20 19:31
    关注

    Your code does essentially this:

    var org *github.Organization
    org.Login = plocalName
    

    org is a nil pointer, it doesn't point to a value, so org.Login tries to de-reference a nil pointer - hence the error. So don't declare org as a pointer type.

    You also have a lot of unnecessary code dealing with pointers, e.g.

    plocalID := &localID
    ..
    if plocalID != nil {
        o.ID = plocalID
        org.ID = plocalID
    }
    

    On that first line you created plocalID and initialized it with &localID. There is no way plocalID can then be a nil pointer, so it doesn't make sense to have the if plocalID != nil { check. You can just get rid of the plocalID and write your code as

    o.ID = &localID
    org.ID = &localID
    
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算