2

I'm trying to create a BST, add a node, and print the data in that node, but I keep getting invalid memory address or nil pointer dereference errors. I know something is wrong with my pointers, and I've been fiddling around with them all afternoon, and I can't seem to get it right. Could someone please take a look and let me know what stupid mistake I'm making?

package main

import "fmt"

type node struct {
    data  int
    left  *node
    right *node
}

type root struct {
    root *node
}

func (bt root) addNode(n *node, data int) {
    if n == nil {
        newNode := node{
            data:  data,
            left:  nil,
            right: nil,
        }
        n = &newNode
        fmt.Println("Works")
    } else if data < n.data {
        bt.addNode(n.left, data)
    } else {
        bt.addNode(n.right, data)
    }
}

func main() {
    tree := root{root: nil}

    tree.addNode(tree.root, 6)
    fmt.Println(tree.root.data)
}

https://go.dev/play/p/Cps4Y5mqYFM

2
  • 1
    The assignment n = &newNode in addNode overwrites the contents of the variable n which is an argument to the method and hence is a local variable in it. The result of this assignment is therefore not visible in the caller because the assignment had modified the copy of the caller's variable. Hence tree.root remains nil, which you could have easily seen if you have printed that value. To modify a pointer-typed variable in a function, you has to pass it a pointer to that pointer and derefence it when assigning—like in *ptrToPtr = someAddress. Commented Apr 26, 2022 at 11:01
  • 1
    To say that in other words, when you call tree.addNode(tree.root) the contents of the variable tree.root, which is nil, is copied into the local variable n of the addNode method, and then that method overwrites the content of that variable. Commented Apr 26, 2022 at 11:03

1 Answer 1

2

As kostix correctly pointed out, in order to modify my tree with that method, I had to pass in a pointer to a pointer to the original tree. Thanks, kostix!

package main

import "fmt"

type node struct {
    data  int
    left  *node
    right *node
}

type root struct {
    root *node
}

func (bt root) addNode(n **node, data int) {
    if *n == nil {
        newNode := node{
            data:  data,
            left:  nil,
            right: nil,
        }
        *n = &newNode
        fmt.Println("Works")
    } else if data < (*n).data {
        bt.addNode(&((*n).left), data)
    } else {
        bt.addNode(&((*n).right), data)
    }
}

func main() {
    tree := root{root: nil}

    tree.addNode(&(tree.root), 6)
    fmt.Println(tree.root.data)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.