Home >Backend Development >Golang >Why am I getting a 'panic: runtime error: invalid memory address or nil pointer dereference' error in my Go code?
When invoking Go, it explicitly panics with the following message:
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 goroutine 2 [syscall]: created by runtime.main /usr/local/Cellar/go/1.0.3/src/pkg/runtime/proc.c:221 goroutine 3 [syscall]: syscall.Syscall6() /usr/local/Cellar/go/1.0.3/src/pkg/syscall/asm_darwin_amd64.s:38 +0x5 syscall.kevent(0x6, 0x0, 0x0, 0xf840085188, 0xa, ...) /usr/local/Cellar/go/1.0.3/src/pkg/syscall/zsyscall_darwin_amd64.go:199 +0x88 syscall.Kevent(0xf800000006, 0x0, 0x0, 0xf840085188, 0xa0000000a, ...) /usr/local/Cellar/go/1.0.3/src/pkg/syscall/syscall_bsd.go:546 +0xa4 net.(*pollster).WaitFD(0xf840085180, 0xf840059040, 0x0, 0x0, 0x0, ...) /usr/local/Cellar/go/1.0.3/src/pkg/net/fd_darwin.go:96 +0x185 net.(*pollServer).Run(0xf840059040, 0x0) /usr/local/Cellar/go/1.0.3/src/pkg/net/fd.go:236 +0xe4 created by net.newPollServer /usr/local/Cellar/go/1.0.3/src/pkg/net/newpollserver.go:35 +0x382
The panic: runtime error: invalid memory address or nil pointer dereference arises when a resource lacks a memory address, known as a nil pointer dereference. This typically happens when you try to use a pointer that points to nothing or when accessing a field of a nil pointer.
To troubleshoot this issue:
In the given code, the panic occurred in the getBody function when attempting to close the res.Body. According to the docs for func (*Client) Do, an error is only returned if caused by client policy or an HTTP protocol error, and successful responses will always contain a non-nil body.
The suggested modification is:
res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close()
By checking for the err before attempting to use res.Body, you can gracefully handle any errors that might have occurred during the request and avoid the panic.
The above is the detailed content of Why am I getting a 'panic: runtime error: invalid memory address or nil pointer dereference' error in my Go code?. For more information, please follow other related articles on the PHP Chinese website!