Go: Panic: Runtime Error: Invalid Memory Address or Nil Pointer Dereference
Question:
When executing a Go program, I encounter the following panic:
panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x38 pc=0x26df] goroutine 1 [running]: main.getBody(0x1cdcd4, 0xf800000004, 0x1f2b44, 0x23, 0xf84005c800, ...) /Users/matt/Dropbox/code/go/scripts/cron/fido.go:65 +0x2bb main.getToken(0xf84005c7e0, 0x10) /Users/matt/Dropbox/code/go/scripts/cron/fido.go:140 +0x156 main.main() /Users/matt/Dropbox/code/go/scripts/cron/fido.go:178 +0x61
Despite attempting to catch errors, I am unable to identify the cause. The program runs on a machine without access to the API servers listed in the code, but I anticipated an appropriate error response.
Can you assist me in resolving this issue?
Answer:
The panic is likely caused by accessing res.Body before checking for a non-nil error in the client.Do() method. According to the documentation for func (*Client) Do, an error is returned if caused by client policy or an HTTP protocol error. However, a non-2xx response does not cause an error, and the resp.Body field still contains a non-nil value.
To resolve the issue, check the error immediately after calling client.Do():
res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close()
The above is the detailed content of Go Panic: How to Debug 'Invalid Memory Address or Nil Pointer Dereference' Errors?. For more information, please follow other related articles on the PHP Chinese website!