skip to content
Alvin Lucillo

Stale pointer bug

/ 1 min read

One common bug is breaking the shared pointer. This happens if you are sharing pointer but modify the pointer instead of mutating the value behind the pointer. This leads to stale pointer. Your consumers expect the pointer to contain your mutated value, but they are referencing an outdated address.

type someObject struct {
	name *string
}

func (s *someObject) process() {
	// bug -- pointer reassignment
	newName := "Wendy"
	s.name = &newName

	// fix -- value mutation
	// *s.name = "Wendy"
}

func main() {
	aName := "Gus"
	x := someObject{name: &aName}
	fmt.Println(*x.name) // Gus

	// copy is preserved for later use
	xCopy := x

	// original object reference modified, not the underlying value
	x.process()

	// somewhere, xCopy is used with the assumption that it contains the expected mutated value
	fmt.Println(*xCopy.name) // Gus; should be Wendy

}