Skip to content

Instantly share code, notes, and snippets.

@erikcorry
Created April 4, 2021 10:38
Show Gist options
  • Save erikcorry/cd285a149cdbfdab12fa40d911e85bb8 to your computer and use it in GitHub Desktop.
Save erikcorry/cd285a149cdbfdab12fa40d911e85bb8 to your computer and use it in GitHub Desktop.
package main
// Demonstrates how taking the address of an embedded struct
// leaks the embedding struct's memory.
type Inner struct {
x int
}
type Outer struct {
b []byte
i Inner
}
func foo() []*Inner {
leak := true // Set to false if you don't want to leak.
inners := []*Inner{}
for i := 0; i < 500_000; i++ {
if i%10_000 == 0 {
println(i)
}
chunk := [1000_000]byte{0}
o := Outer{b: chunk[:], i: Inner{x: 5}}
if leak {
// Keeps o (and thus chunk) alive.
inners = append(inners, &o.i)
} else {
copy := o.i
// The copy of o.i is not embedded in o, so it doesn't keep o alive.
inners = append(inners, &copy)
}
}
return inners
}
func main() {
result := foo()
println(len(result))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment