Skip to content

slices: Incorrect implementation of slices.Insert and slices.Replace #60138

@merykitty

Description

@merykitty

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?

[1 2 5 6 3 4]

What did you see instead?

[1 2 3 4 3 4]

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.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions