Created
April 4, 2021 10:38
-
-
Save erikcorry/cd285a149cdbfdab12fa40d911e85bb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, ©) | |
} | |
} | |
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