Skip to content

document that decoded byte slice shares underlying array with buffer #62

@LukasGelbmann

Description

@LukasGelbmann

If you decode a struct which contains a slice of bytes, the returned slice shares the same underlying array with the buffer passed to Decode().

The consequences are:

  • If the buffer is later overwritten, the contents of the decoded slice change (see demonstration below).
  • If a (potentially large) buffer is no longer in use, the memory underlying array can't be freed as long as there is a reference to the decoded slice of bytes.

I think these consequences aren't intended. It seems better for Decode() to return a copy of the slice of bytes.

package main

import "go.dedis.ch/protobuf"
import "fmt"

func main() {
	type foo struct{ Bar []byte }
	buf, _ := protobuf.Encode(&foo{[]byte{44, 45}})

	var decoded foo
	protobuf.Decode(buf, &decoded)
	fmt.Println(decoded) // {[44 45]}

	buf[len(buf)-1] = 99
	fmt.Println(decoded) // {[44 99]}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions