runtime error: invalid memory address or nil pointer dereference

created at 04-09-2022 views: 7

problem

Pointer Basics

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, and & represents the address of a value. For pointers, we must understand that the pointer stores the address of a value, but the pointer itself also needs an address to store.

As above p is a pointer whose value is the memory address 0xc04204a080 And the memory address of p is 0xc042068018

The memory address 0xc04204a080 stores the value 1 Address 0xc042068018 0xc04204a080 Value 0xc04204a080 1

Error instance

In golang, if we define a pointer and assign it a value like a normal variable, for example, the following 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 this error is that when go initializes the pointer, it will assign nil to the value of the pointer i, but the value of i represents the address of *i, if nil, the system has not given *i assigns an address, so assigning a value to *i at this time will definitely go wrong

solution

Solving this problem is very simple. Before assigning a value to a pointer, you can create a block of memory and assign it to the assignment object.

package main

import "fmt"
func main() {
    var i *int
    i = new(int)
    *i = 1
    fmt.Println(i, &i, *i)
}
Go
Please log in to leave a comment.