github.com/zach-klippenstein/go@v0.0.0-20150108044943-fcfbeb3adf58/test/gcstring.go (about)

     1  // run
     2  
     3  // Copyright 2014 The Go Authors.  All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test that s[len(s):] - which can point past the end of the allocated block -
     8  // does not confuse the garbage collector.
     9  
    10  package main
    11  
    12  import (
    13  	"runtime"
    14  	"time"
    15  )
    16  
    17  type T struct {
    18  	ptr **int
    19  	pad [120]byte
    20  }
    21  
    22  var things []interface{}
    23  
    24  func main() {
    25  	setup()
    26  	runtime.GC()
    27  	runtime.GC()
    28  	time.Sleep(10*time.Millisecond)
    29  	runtime.GC()
    30  	runtime.GC()
    31  	time.Sleep(10*time.Millisecond)
    32  }
    33  
    34  func setup() {
    35  	var Ts []interface{}
    36  	buf := make([]byte, 128)
    37  	
    38  	for i := 0; i < 10000; i++ {
    39  		s := string(buf)
    40  		t := &T{ptr: new(*int)}
    41  		runtime.SetFinalizer(t.ptr, func(**int) { panic("*int freed too early") })
    42  		Ts = append(Ts, t)
    43  		things = append(things, s[len(s):])
    44  	}
    45  	
    46  	things = append(things, Ts...)
    47  }
    48