Source file test/fixedbugs/issue8004.go

     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  package main
     8  
     9  import (
    10  	"reflect"
    11  	"runtime"
    12  	"unsafe"
    13  )
    14  
    15  func main() {
    16  	test1()
    17  	test2()
    18  }
    19  
    20  func test1() {
    21  	var all []interface{}
    22  	for i := 0; i < 100; i++ {
    23  		p := new([]int)
    24  		*p = append(*p, 1, 2, 3, 4)
    25  		h := (*reflect.SliceHeader)(unsafe.Pointer(p))
    26  		all = append(all, h, p)
    27  	}
    28  	runtime.GC()
    29  	for i := 0; i < 100; i++ {
    30  		p := *all[2*i+1].(*[]int)
    31  		if p[0] != 1 || p[1] != 2 || p[2] != 3 || p[3] != 4 {
    32  			println("BUG test1: bad slice at index", i, p[0], p[1], p[2], p[3])
    33  			return
    34  		}
    35  	}
    36  }
    37  
    38  type T struct {
    39  	H *reflect.SliceHeader
    40  	P *[]int
    41  }
    42  
    43  func test2() {
    44  	var all []T
    45  	for i := 0; i < 100; i++ {
    46  		p := new([]int)
    47  		*p = append(*p, 1, 2, 3, 4)
    48  		h := (*reflect.SliceHeader)(unsafe.Pointer(p))
    49  		all = append(all, T{H: h}, T{P: p})
    50  	}
    51  	runtime.GC()
    52  	for i := 0; i < 100; i++ {
    53  		p := *all[2*i+1].P
    54  		if p[0] != 1 || p[1] != 2 || p[2] != 3 || p[3] != 4 {
    55  			println("BUG test2: bad slice at index", i, p[0], p[1], p[2], p[3])
    56  			return
    57  		}
    58  	}
    59  }
    60  

View as plain text