Skip to content

Implicit Memory Aliasing

What does this mean ?

In case you dereference sequentially within the loop and you know for sure that nothing is leaking the pointer, you might get away with ignoring this check. However the job of the linter is precisely to report code patterns that could cause issues, so it's a good idea to fix it.

What can happen ?

The warning Implicit memory aliasing in for loop means, in short, that you are taking the address of a loop variable.It might lead to unintended behaviour

Recommendation

A for loop in Go will only use one iterator variable whose value gets updated in each loop operation. Since it’s just a single variable, its address is constant and doesn’t change. If not used carefully, it might lead to unintended behaviour.

Sample Code

Vulnerable :

package main

import "fmt"

func main() {
    var output []*int
    nums := []int{1, 2, 3}

    for _, num := range nums {
        output = append(output, &num)
    }

    fmt.Println("Value: ", *output[0], *output[1], *output[2])
    fmt.Println("Address: ", output[0], output[1], output[2])
}

Non Vulnerable :

package main

import "fmt"

func main() {
    var output []*int
    nums := []int{1, 2, 3}

    for i := range nums {
        output = append(output, &nums[i])
    }

    fmt.Println("Value: ", *output[0], *output[1], *output[2])
    fmt.Println("Address: ", output[0], output[1], output[2])
}

References