douzhi3776 2016-05-24 23:31
浏览 54
已采纳

Golang,nil指针取消引用或无效的内存地址

my code works perfectly until I want to scale it using many concurrent calls. It works by asking the client a Get request.

This is what I'm getting:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x400da9]

goroutine 125 [running]:
runtime.panic(0x697480, 0x850d13)
    /usr/lib/go/src/pkg/runtime/panic.c:279 +0xf5
main.concurrent(0x25e5)
    /home/maker/go/src/GoBot/GoBot.go:19 +0x1a9
created by main.main
    /home/maker/go/src/GoBot/GoBot.go:51 +0x224

I think I'm not properly handling the error and when making a lot of requests it crashes.

func concurrent(n uint64) {
    for i := n; i < n+11; i++ {
            member,  err := s.GetUser(i)
            output <- fmt.Sprint(member.Username) //This is line 19 that triggers the error
            if err != nil && member != nil {
              continue
           }
     }
defer wg.Done()
}

How can I solve this? References for s.GetUser here: https://github.com/njasm/gosoundcloud/blob/master/soundcloud.go#L274

  • 写回答

1条回答 默认 最新

  • douzhan8303 2016-05-24 23:38
    关注

    Firstly, you could prevent the panic by checking the return value of GetUser which you're currently ignoring;

            member,  err := s.GetUser(i)
            if err != nil {
               // handle error
            }
            if member != nil { // prevents the panic attempting to access Username on nil instance of user/member
                 output <- fmt.Sprint(member.Username) //This is line 19 that triggers the error
                if err != nil && member != nil {
                  continue
               }
           }
    

    Beyond that, what is GetUser doing? If it's making an HTTP GET, then typically the application would block until it returns, meaning chances are, if you check your error, there will be one like an HTTP 404, 403, 500 ect.

    If the call to GetUser were concurrent, then you could run into an issue where the code below attempts to access the member.Username before GetUser has returned causing the nil panic but I don't see how that could happen since you have no goroutine there. It should just be a simple blocking call. If you find the above suggestion doesn't lead you to the root cause of your problem, then edit your question with the results from GetUser and it's implementation and I'll look into it further.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?