Home >Backend Development >Golang >golang: invalid memory address or nil pointer dereference

golang: invalid memory address or nil pointer dereference

WBOY
WBOYforward
2024-02-08 21:12:10888browse

golang: invalid memory address or nil pointer dereference

php editor Xiaoxin here introduces a common error message: "golang: Invalid memory address or zero pointer dereference". When developing applications using the Golang programming language, you sometimes encounter this error. It usually indicates that an invalid memory address or zero pointer is dereferenced in the code. This error may cause the program to crash or produce unpredictable behavior. Next, we will explore some common causes and solutions that may cause this error to help developers better understand and solve this problem.

Question content

Execute me Now I have a program named HelloWorld and the project structure is

aaa.go

package aaa

import (
    "HelloWorld/test/bbb"
)

var aa = bbb.Bb

func World() {
    aa.Hello()
}

bbb.go

package bbb

import "HelloWorld/test/ccc"

var Bb *ccc.Config

ccc.go

package ccc

import "fmt"

type Config struct {
    C int
}

func ConfigInit() *Config {
    return &Config{C: 10}
}

func (c *Config) Hello() {
    fmt.Println(c.C)
}

main.go

package main

import (
    "HelloWorld/test/aaa"
    "HelloWorld/test/bbb"
    "HelloWorld/test/ccc"
)

func init() {
    bbb.Bb = ccc.ConfigInit()
}

func main() {

    aaa.World()
}

Now when I run the program it will panic: Runtime error: invalid memory address or nil pointer dereference

But when I change

main.go

import (
    "HelloWorld/test/bbb"
    "HelloWorld/test/ccc"
)

func init() {
    bbb.Bb = ccc.ConfigInit()
}

func main() {

    // aaa.World()
    var aa = bbb.Bb
    aa.Hello()
}

Can output the correct value

10 I don't know why the definition var aa = bbb.Bb in bbb.go is incorrect

I don't understand why it is a null pointer

Solution

If you look at the picture above, it shows the import and variable initialization flow. Now, in the first case

aaa.world. The variable nil in the world function is set to nil because even before the init function in main runs, once init runs bb points to valid memory, but Prior to this, bb in package bbb had never been initialized. Let us consider the second case, here the init function also gives bb a valid memory, but the problem here is that aa is reallocated to bb, which points to the valid memory, after allocation aa is also like this.

The above is the detailed content of golang: invalid memory address or nil pointer dereference. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete