Skip to content

cmd/compile: trailing blank variable causes nil pointer panic in array range #81697

Closed

Description

@0xkohe

Go version

Reproduced with all three toolchains:

go version go1.26.8 linux/amd64
go version go1.27.1 linux/amd64
go version go1.28-devel_12c76d44 Tue Sep 22 02:16:50 2026 -0700 linux/amd64

The development version is pinned to official Go commit 12c76d447f576e6c14c566c8524c13a0c0d476b9, rather than a moving master reference.

Output of go env / environment

Test environment: Debian 12 container, Linux/amd64, gc compiler. The fresh container image is pinned to:

golang@sha256:69a7b9788769bec032d238959b61854e9ae87f57be9029ec04e9885fabf99195

Relevant go env values measured in the reproduction environment with Go 1.27.1:

GOARCH=amd64
GOHOSTARCH=amd64
GOHOSTOS=linux
GOOS=linux
GOVERSION=go1.27.1
GOROOT=/usr/local/go
GOTOOLDIR=/usr/local/go/pkg/tool/linux_amd64
GOENV=
GOFLAGS=
GOEXPERIMENT=
GOTOOLCHAIN=local
CGO_ENABLED=0
GOCACHE=/work/cache
GOPATH=/work/gopath
GOMODCACHE=/work/modcache
GOPROXY=off
GOSUMDB=off

Each build/run pair used a fresh container, a cleared environment, explicit GOENV=off, GOTOOLCHAIN=local, CGO_ENABLED=0, and disabled networking. The empty GOENV above is what go env reports with GOENV=off. Build caches were shared only between cases using the same toolchain. The older release and development compiler used the same container base with GOROOT=/opt/go. All containers shared the host's Linux kernel and amd64 CPU; no other OS, architecture, or gccgo was tested.

What did you do?

Save this complete, dependency-free program as repro.go:

package main

func main() {
    var p *[3]int
    for i, _ := range (*p) {
        print(i)
    }
}

Compile it and run the resulting executable:

go build -o repro repro.go
./repro

Then remove only , _, keeping the nil pointer type, array length, parentheses, and loop body unchanged:

package main

func main() {
    var p *[3]int
    for i := range (*p) {
        print(i)
    }
}

Replace repro.go with the second program and rebuild it with the same command. The files differ only by the bytes , _.

I also tested the range headers in the results table below. Every case was built and run with default compiler flags, -gcflags=-N, -gcflags=-l, and -gcflags='-N -l' on each toolchain. The test commands additionally used -p 2 to bound build parallelism.

What did you see happen?

On all three toolchains and all four configurations, the for i, _ := range (*p) program built successfully but exited with code 2. Its stdout was empty and stderr began with:

panic: runtime error: invalid memory address or nil pointer dereference

Removing only , _ made the program print 012 to stderr and exit with code 0. Both versions used the same nil *[3]int.

Results below were identical with default flags, -N, -l, and -N -l. “012” means empty stdout, stderr exactly 012, and exit code 0. “nil panic” means empty stdout, the nil-dereference panic above, and exit code 2.

Range header, with nil p *[3]int Go 1.26.8 Go 1.27.1 Development 12c76d44
for i := range p 012 012 012
for i, _ := range p 012 012 012
for i := range *p 012 012 012
for i, _ := range *p nil panic nil panic nil panic
for i := range (*p) 012 012 012
for i, _ := range (*p) nil panic nil panic nil panic

For example, the Go 1.27.1 default build of the parenthesized blank case produced this complete stderr:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x47db10]

goroutine 1 [running]:
main.main()
	/work/sources/range-paren-deref-blank.go:5 +0x10

A corresponding pair that counted iterations and checked the index sequence without printing showed the same difference on every tested toolchain/configuration: the blank-variable case panicked, and the no-blank case passed. A two-value control, for i, v := range (*p) { print(i, v) }, panicked as expected.

What did you expect to see?

All six cases should produce 012 and exit successfully. In this gc-based reproduction, print writes the digits to stderr; no newline is requested by the program.

The range-clause specification makes a final blank iteration variable equivalent to omitting it. With at most one effective iteration variable, a constant range expression or constant len means the range expression is not evaluated.

The length-and-capacity specification makes len(*p) constant here: the expression has array type and contains no channel receive or nonconstant function call. Consequently, *p should not be evaluated, and the nil pointer should not cause a panic.

Related reports

  • #4173 reported a nil-pointer panic with a blank second iteration variable. Its regression test ranges over the nil pointer variable directly; this reproducer explicitly dereferences it.
  • #73476 concerns a single-variable range where adding parentheses around *p changed the behavior. This reproducer keeps the parentheses unchanged and varies only the final blank variable.

This may be related to those reports; please consolidate it with an existing issue if appropriate.

Discovery context

I encountered this behavior while developing executable Go semantics in the K Framework and comparing specification-derived test cases against the Go compiler. The reproducer above uses only the Go toolchain.

A snapshot of the semantics implementation is available at ba97042.

Activity

  1. thepudds commented on Sep 23, 2026

    @thepudds
    Member

    Thanks for reporting this.

    This seemed to bisect to 336626b:

      first BAD:   336626bac4 | 2025-04-21 22:50 | cmd/compile: ensure we evaluate side effects of len() arg
      GOOD parent: 8af32240c6 | 2025-04-21 22:50 | cmd/compile: don't evaluate side effects of range over array
    

    CC @randall77

  2. gopherbot commented on Sep 23, 2026

    @gopherbot
    Contributor

    Change https://go.dev/cl/837325 mentions this issue: cmd/compile: don't evaluate range expression for a blank second variable

  3. griesemer commented on Sep 23, 2026

    @griesemer
    Contributor

    @0xkohe Thanks for reporting.

    As an aside, much of this issue report (if not all) looks LLM-generated, with plenty of irrelevant information. All that was needed is the simple example:

    package main
    
    func main() {
    	var p *[3]int
    	for i, _ := range *p {
    		_ = i
    	}
    }

    with playground link plus a short explanation as to what is wrong.

    In the future, please reduce the amount of text to the minimum needed; thanks.

  4. 0xkohe commented on Sep 23, 2026

    @0xkohe
    Author

    @griesemer Thanks for the feedback. Understood.
    I’ll keep future reports more concise.

  5. randall77 commented on Sep 23, 2026

    @randall77
    Contributor

    I think the current behavior is correct. The spec says:

    The range expression x is evaluated before beginning the loop, with one exception: if at most one iteration variable is present and x or [len(x)](https://go.dev/ref/spec#Length_and_capacity) is [constant](https://go.dev/ref/spec#Constants), the range expression is not evaluated.
    

    So if there is more than one iteration variable, *p is evaluated and we get a nil pointer exception.
    With only a single iteration variable, *p is not evaluated and we get 012 printed.

  6. 0xkohe commented on Sep 23, 2026

    @0xkohe
    Author

    Thanks. The preceding sentence says that if the last iteration variable is "_", the range clause is equivalent to the same clause without it.

    The spec also gives "for i, _ := range testdata.a" as an example and says that "testdata.a" is never evaluated.

    var testdata *struct {
    	a *[7]int
    }
    for i, _ := range testdata.a {
    	// testdata.a is never evaluated; len(testdata.a) is constant
    	// i ranges from 0 to 6
    	f(i)
    }
    

    Wouldn't that make "for i, _ := range *p" equivalent to the single-variable case for this rule?

  7. randall77 commented on Sep 23, 2026

    @randall77
    Contributor

    Good point, the spec is fighting with itself here.

    And indeed, that testdata.a example in the spec panics at tip. Despite the spec saying it shouldn't. (It starts panicing at Go 1.25.)
    So I guess we need to introduce a special case for the second variable being _.

  8. griesemer commented on Sep 23, 2026

    @griesemer
    Contributor

    This is clearly an esoteric case - we've stumbled over this a couple of times over the years, "fixed" it differently, and then it took a while before we noticed the unexpected/expected behavior.

    I think we need to rethink what the spec should actually say here (and fix its inconsistency).

    There's a good argument to be made for the current fix: "if the last iteration variable is "_", the range clause is equivalent to the same clause without it" allows a user or a tool (gofmt) to simplify code irrespective of context.

    There's a good argument to keep the current behavior: for instance var _ = (*p)[0] does panic for a nil p even though the result is assigned to _. It's odd that this is not the case in a for range.

  9. randall77 commented on Sep 23, 2026

    @randall77
    Contributor

    If we're open to a spec change, I would just get rid of the "not evaluated" case entirely.

    Not sure it is worth the churn though.

  10. griesemer commented on Sep 23, 2026

    @griesemer
    Contributor

    I was thinking of leaving away the "if the last iteration variable is "_", the range clause is equivalent to the same clause without it" clause. It won't affect existing programs (the current behavior is there since approx. a year) and simplifies the spec.

  11. randall77 commented on Sep 23, 2026

    @randall77
    Contributor

    I would be ok with that also.

  12. cuonglm commented on Sep 23, 2026

    @cuonglm
    Member

    I was thinking of leaving away the "if the last iteration variable is "_", the range clause is equivalent to the same clause without it" clause. It won't affect existing programs (the current behavior is there since approx. a year) and simplifies the spec.

    This sounds reasonable to me, less (if) is more.

  13. rsc commented on Sep 25, 2026

    @rsc
    Contributor

    (I'm not following the issue tracker closely, but Robert asked me to take a look at this and add my opinion publicly.)

    I would argue strongly for for x, _ := range and for x := range having identical meanings.

    • If you'd asked me last week what the difference was between for x, _ := range and for x := range, I'd have said there is no difference at all, and if you'd pressed me for an actual difference, I'd never have imagined one can panic where the other does not.
    • If anyone does want a panic check, they should write it explicitly and clearly; ", _" is not a panic check.
    • Simplifiers—both programs and people—should have simple rules for simplifying programs. The simple rule has always been (or was until Go 1.25) that x, _ := range and x := range are the same. We should keep that rule. It's true that programs can deal with more complex rules, but people are not as good at it.
    • This is the historical behavior through Go 1.24; Go 1.25 changed the behavior. We should revert it for compatibility if nothing else. It clearly doesn't affect much code, or we'd have gotten the report sooner, but we should not make language changes just because they don't affect much.

    Perhaps most compellingly, the original description of this rule, in CL 4444050 used a for x, _ := range loop to illustrate the rule about the expression not evaluating. I can only conclude that the spec used that specific example to illustrate that the two rules do in fact compose: (1) second blank is same as one variable, (2) one variable does not evaluate.

    That example didn't panic 15 years ago, and I believe it still shouldn't panic today.

  14. griesemer commented on Sep 25, 2026

    @griesemer
    Contributor

    Indeed, this is pretty convincing - thanks @rsc .
    I retract my suggestion - I'm not sure why I missed the example, both in the spec and further up in this issue.

  15. added a commit that references this issue on Sep 25, 2026
    dd5f863
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions