What did you do?
Crafted an example such that the memory referenced by the result overlaps with the insert-from slice, playground
a := []int{1, 2, 3, 4, 5, 6, 7, 8}
b := a[:4] // 1, 2, 3, 4
c := a[4:6] // 5, 6
res := slices.Insert(b, 2, c...)
fmt.Println(res)
What did you expect to see?
What did you see instead?
Note: This is because the implementation of slices.Insert slides the upper range of the first operand forward before copying the content of the third operand into the freed space. This risks overwrite the content in that operand. I believe slices.Replace suffers the same issue, too.
A conservative solution is to create a temporary buffer to copy the content of the second slice into before sliding the first one, while a more aggressive one would be to do pointer arithmetic to check the aliasness.
What did you do?
Crafted an example such that the memory referenced by the result overlaps with the insert-from slice, playground
What did you expect to see?
What did you see instead?
Note: This is because the implementation of
slices.Insertslides the upper range of the first operand forward before copying the content of the third operand into the freed space. This risks overwrite the content in that operand. I believeslices.Replacesuffers the same issue, too.A conservative solution is to create a temporary buffer to copy the content of the second slice into before sliding the first one, while a more aggressive one would be to do pointer arithmetic to check the aliasness.