Pointer to itself

Hello everyone

I have a question to the garbage collector.

For a pattern for programming I need to store a pointer to an instance of a struct in the instance itself. My proof of concept works for what I want to achieve but I’m afraid the garbage collector will look at the instance and see that there is still a reference to it even when the reference is hold by the instance itself.

Am I right that this will cause problems or is the garbage collector smart enough to see that the reference is no longer needed?


It’s fine to have an object that points to itself. The existence of a pointer to some value is not enough to keep an object alive; the pointer must also be reachable from a root, such as directly or indirectly via a global or function-local variable. Otherwise, for any memory to ever be cleaned up, you’d have to explicitly set fields to nil!

You could have a pair of nodes, each node pointing to the other and if you have a pointer variable holding on to one of those nodes, both will “survive” garbage collection. If the function variable goes out of scope, or is set to some other pointer value, then both of those self-referencing nodes will be collected (unless somewhere else in the program is holding on to a pointer to one or both of those two nodes):

package main

import "runtime"

type N struct {
    Next *N
    Value int

func main() {
    a := &N{Value: 1}
    b := &N{Value: 2}
    a.Next = b
    b.Next = a    // make each node reference the other
    a = nil    // this is OK because this function call
               // still knows about `b` and `b` references
               // `a`.
    b = nil    // now nothing references `a` or `b` except
               // `a` and `b` themselves. Nothing in the
               // program would care if these variables
               // were freed, so free them.
    // at this point, both `a` and `b` should be freed
    // because even though they hold pointers to each
    // other, it's a closed loop and nothing else is
    // holding a pointer to keep them alive.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.