Skip to content

Instantly share code, notes, and snippets.

@Neurostep
Forked from erikcorry/leak.go
Created May 3, 2021 10:34
Show Gist options
  • Save Neurostep/51d3262e82b9aeb645d85aead293f298 to your computer and use it in GitHub Desktop.
Save Neurostep/51d3262e82b9aeb645d85aead293f298 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