6 April 2021 / 1 min read
Golang nil pointer dereference
Go: panic: runtime error: invalid memory address or nil pointer dereference
Problem statement
Sample code
func ( c * Calculate ) Sum () int64 {
var cal * Calculate // Initialize cal to <nil>
fmt. Println ( " SUM = " , cal. Sum ()) // calling method on <nil> creates panic
Running code:
Output:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code = 0x1 addr = 0x0 pc = 0x497783]
main.(*Calculate ).Sum( ... )
/tmp/sandbox800773077/prog.go:12
/tmp/sandbox800773077/prog.go:17 +0x23
Why is issue:
The uninitialized pointer “cal” in the main function is nil, and so can’t call method on the nil pointer.
If “cal” is nil, an attempt to evaluate “*cal” will cause a run-time panic.
Solution
var cal * Calculate = new ( Calculate ) // Initialize cal to &{0 0}
fmt. Println ( " SUM " .cal. Sum ()) // calling method cal Worked
Output :
ref. link