Tag Archives: Runtime error: invalid memory address or nil pointer dereference

Runtime error: invalid memory address or nil pointer dereference [How to Solve]

Basic knowledge of pointers

package main

import " fmt "

func main() {
    var p * int 
    p = new ( int )
     *p = 1 
    fmt.Println(p, &p, * p)
}

Output
0xc04204a080 0xc042068018 1

In Go, * represents the value stored in the pointer address, & represents the address
to take a value. For pointers, we must understand that the pointer stores the address of a value, but the pointer itself also needs the address to store the
above p is a pointer , His value is the memory address 0xc04204a080
and the memory address of p is 0xc042068018
memory address 0xc04204a080 The stored value is 1
address 0xc042068018 0xc04204a080
value 0xc04204a080 1
error example
in golang if we define a pointer and assign it like a normal variable, such as the following The code

package main

import " fmt "
func main() {
    var i * int 
    *i = 1 
    fmt.Println(i, &i, * i)
}

Will report such an error

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code= 0x1 addr= 0x0 pc= 0x498025 ]

The reason for reporting this error is that when go initializes the pointer, it assigns the value of pointer i to nil, but the value of i represents the address of *i. If nil, the system has not assigned an address to *i, so at this time, * i Assignment will definitely go wrong.
Solving this problem is very simple. You can create a block of memory and allocate it to the assignment object before assigning the pointer.

package main

import " fmt "
func main() {
    var i * int 
    i = new ( int )
     *i = 1 
    fmt.Println(i, &i, * i)
}

end!