Skip to content
Code quality and reliability Reviewed 2026-09-13

Implicit Memory Aliasing

What does this mean ?

Several saved pointers may accidentally refer to one reused loop variable. This is a correctness issue; a security impact requires an additional consequence, such as applying a decision to the wrong record.

The blanket claim that Go always reuses a declared range variable is outdated. With Go 1.22 language semantics, variables declared by := in the loop receive separate instances for each iteration. The module's language version matters. Assigning into an existing variable with = still reuses it. See the Go 1.22 release notes.

What can happen ?

Pointers to the reused variable all observe its final value. Even distinct pointers to copied values do not point back into the original slice. Choose the behavior the application actually needs.

Recommendation

When pointers must refer to original slice elements, take their addresses by index. If independent snapshots are intended, copy values deliberately instead. Account for later slice replacement or append operations when designing ownership and mutation behavior.

Sample Code

These fragments run inside a Go function.

Incorrect: every pointer refers to the same variable, including in Go 1.22+:

nums := []int{1, 2, 3}
var output []*int
var num int
for _, num = range nums {
    output = append(output, &num)
}

Correct when references to the slice elements are intended:

nums := []int{1, 2, 3}
var output []*int
for i := range nums {
    output = append(output, &nums[i])
}

Regression test: verify pointed-to values are 1, 2, 3, then assign *output[0] = 9. Only nums[0] should change. Run with the module's declared Go language version.

References