Skip to content

append overwrites memory in extremely non-intuitive/difficult to debug way #28780

@fosrias

Description

@fosrias

What version of Go are you using (go version)?

go 1.11.1

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

Reproducible on go playground and on OSX

What did you do?

https://play.golang.org/p/m5q_dukI-21

What did you expect to see?

Same, correct sorted value.

What did you see instead?

Different values.

What is happening in this algorithm, is that in the incorrect sort, when it gets to sorting the last 2, it appends the 2 onto first := A[:i] ([1, 2]. When this happens, it appears to overwrite first memory address of last := A[:i] with the appended value, discarding the prior value that was desired to be maintained. Thus, instead of last being [3, 4], it is at that point [2,4], which when appended on insert result, gives the wrong answer.

The work around is to copy the slices first. Then all works fine.

This just feels wrong that append works this way and may be a bug. At the very least, it seems some documentation on this is warranted to highlight this non-intuitive behavior that appending to a partial slice can overwrite the original slice's memory allocation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions