Skip to content
Latchkey

Go "panic: runtime error: invalid memory address" in Tests - Fix in CI

A test panicked dereferencing a nil pointer, calling a method on a nil interface, or writing to a nil map. The panic aborts the test binary and go test reports it with the goroutine stack at the crash.

What this error means

A test crashes with panic: runtime error: invalid memory address or nil pointer dereference and a [signal SIGSEGV] line, followed by a stack trace pointing at the offending line. The test that panicked fails and the run exits non-zero.

go test output
--- FAIL: TestLoad (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x...]

goroutine 19 [running]:
github.com/yourorg/app.(*Client).Do(...)
	client.go:33 +0x18

Common causes

Dereferencing a nil pointer or interface

A constructor returned nil (often alongside an error the test ignored), or a struct field was never initialized, and the test then called a method or field on it.

Writing to a nil map

A map declared but never made with make panics on assignment. A zero-value map field is a common culprit in test setup.

An ignored error masking a nil result

The test discarded an error and used the (nil) value, so the panic surfaces later instead of at the real failure point.

How to fix it

Read the crash frame and guard the nil

  1. Find the top frame in the stack - it names the file:line that dereferenced nil.
  2. Check the error you ignored just before it; handle it instead of discarding it.
  3. Initialize the pointer/map/struct, or add a nil check before use.

Initialize maps and check constructor errors

client_test.go
m := make(map[string]int)   // not: var m map[string]int
c, err := NewClient()
if err != nil { t.Fatalf("NewClient: %v", err) }

How to prevent it

  • Never ignore errors from constructors in tests; use t.Fatalf on failure.
  • Initialize maps with make and pointers before use.
  • Run go vet and a linter to catch obvious nil-deref patterns.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →