-
-
Save Neurostep/51d3262e82b9aeb645d85aead293f298 to your computer and use it in GitHub Desktop.
This file contains hidden or 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