invalid memory address
Go Programming Language
Severity: CriticalWhat Does This Error Mean?
Go panics when code tries to read or write memory that has no valid address. This almost always means a pointer is nil — it points to nothing. You must initialize the value the pointer points to before using it.
Affected Models
- Go 1.21
- Go 1.22
- Go 1.23
- Go 1.24
Common Causes
- Calling a method on a nil pointer receiver
- Dereferencing a pointer (*p) before checking if p is nil
- Returning a pointer from a function that returns nil on error, then using it without checking
- Accessing a field of a struct through an uninitialized pointer
- A zero-value struct field that is a pointer, used before being set
How to Fix It
-
Read the stack trace and find the exact line that panicked.
Go tells you the file and line number. Go to that line — you will find a pointer being dereferenced.
-
Add a nil check before using any pointer: if p == nil { return error or handle it }
Never assume a pointer is non-nil. Always guard access with an explicit nil check.
-
When a function returns (value, error), always check the error before using the value.
resp, err := doSomething(); if err != nil { return err } — then use resp. Don't skip the error check.
-
Initialize struct pointer fields explicitly before using them.
type Config struct { Logger *log.Logger } — if Logger is never set, calling config.Logger.Print() will panic.
-
Use pointer-safe patterns: prefer returning concrete values over pointers when the nil case is possible.
Returning a struct value (not a pointer) means the caller always gets a usable zero-value struct.
When to Call a Professional
If this panic occurs inside a critical path or after a complex chain of function calls, ask a senior developer to trace the nil's origin. Sometimes nil propagates from a failed initialization far upstream.
Frequently Asked Questions
Is 'invalid memory address' the same as 'nil pointer dereference'?
They appear together in the same panic message. The full message is: 'runtime error: invalid memory address or nil pointer dereference'. In practice, nil pointer dereference is the most common cause.
Can a method with a pointer receiver be called on a nil pointer?
Yes — the method is called, but accessing any field inside it will panic. You can write nil-safe methods by checking if the receiver is nil at the top: if p == nil { return }.
Why do Go pointers default to nil instead of a zero value?
A pointer's zero value is nil — it means 'no value has been assigned yet'. This is intentional: Go wants you to explicitly initialize values. Use new(T) or &T{} to create a non-nil pointer.