Home > Net >  What happens when I range over an uninitialized pointer to array in golang
What happens when I range over an uninitialized pointer to array in golang

Time:05-12

I have this code

var j *[33]byte

for i := range j {
    fmt.Println(j[i])
}

Now when I run this code I get nil pointer dereference error when I try access values in j. I'm not sure why I was even able to enter the loop in the first place considering my pointer is uninitialized.

I know an uninitialized array has all its values set to their zero value. That is

var a [5]int

Will have a default value of [0, 0, 0, 0, 0].

But I don't understand what golang does when you don't initialize a pointer to an array. Why is range able to range over it even though its nil?

CodePudding user response:

Go has a zero value defined for each type when you initialize a variable with var keyword (this may change when using :=, ideally used when need copies of values or specific values). In the case of the pointer the zero value is nil (also maps, interfaces, channels, slices, and functions) in case of array of type int the zero value is 0.

So, to answer your question, Go is able to iterate because you have 33 valid spaces idependently of what value is inside of that position. You can check the diference between slices and arrays on the Golang documentation to have more insights on why is that.

CodePudding user response:

From the Go spec Range Clause:

... For an array, pointer to array, or slice value a, the index iteration values are produced in increasing order...

so as a convenience the Go language is dereferencing the pointer with the intent to iterating over its elements. The fact that the pointer is nil is a simple programming error. If this can occur, one should have a runtime check in place to guard against it.

Static analysis may be able to detect this type of bug ahead of time - but what if the variable j is accessible from another goroutine - how would the compiler know for sure that another goroutine may update it to a non-nil value right before the range loop is reached?

  • Related