Incorrect access of indexable resource ('Range Error')


Go's for ... range constructs allocate a single iteration variable for the loop's duration, which can cause confusion when addresses of this variable are stored or used beyond a single iteration. Since the iteration variable's address remains constant, subsequent iterations overwrite the previously referenced values, leading to unexpected results, particularly when using go routines or deferred functions within the loop.


✅ Create a New Variable Inside the Loop

Declare a new local variable within the loop's scope to hold the iteration value. This ensures a unique address is used for each iteration.

for _, n := range []someStruct{{1}, {2}, {3}, {4}} {
localVar := n
// Use localVar instead of n

✅ Use Indexed Addressing

Instead of the iteration variable, directly reference the indexed element within the array or slice.

for i := range mySlice {
// Use &mySlice[i] to obtain a stable address

❌ Do Not Store the Address of the Iteration Variable

Avoid taking the address of the iteration variable and storing it, as it leads to all references pointing to the same memory location.

❌ Avoid Using the Iteration Variable's Address in Goroutines

Using the iteration variable's address directly in goroutines can cause race conditions or logical errors, as the variable's value may change before the goroutine accesses it.


Associated CWE


To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=go_gosec_memory_memory_aliasing

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=go_gosec_memory_memory_aliasing

Ready to take the next step? Learn more about Bearer Cloud.