On Tuesday, April 21, 2020 at 8:13:17 PM UTC-4, Ian Lance Taylor wrote: > > On Tue, Apr 21, 2020 at 8:17 AM T L <tapi...@gmail.com <javascript:>> > wrote: > > > > And is the runtime.KeepAlive call in the following program essential to > keep the correctness? > > > > package main > > > > import ( > > "fmt" > > "unsafe" > > "reflect" > > "runtime" > > ) > > > > func main() { > > a := [6]byte{'G', 'o', 'o', 'g', 'l', 'e'} > > bs := []byte("Golang") > > hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs)) > > hdr.Data = uintptr(unsafe.Pointer(&a)) > > > > runtime.KeepAlive(&a) // Is this line essential here? > > > > hdr.Len = 2 > > hdr.Cap = len(a) > > fmt.Printf("%s\n", bs) // Go > > bs = bs[:cap(bs)] > > fmt.Printf("%s\n", bs) // Google > > } > > I do not think the runtime.KeepAlive is required. Setting the Data > field using a *SliceHeader should keep the value alive. > > Ian >
Many thanks for the answers. I have another question, which doesn't matter with or without the runtime.KeepAlive call. We know that assignment in Go is not atomic. Is it possible that when the assignment "hdr.Data = uintptr(unsafe.Pointer(&a))" is half done, the stack is resized, so the address of a might be changed (assume a is allocated on stack), the hdr.Data will be assigned the old invalid value? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4c9d0b1d-2fd1-4d41-9b0f-26cf93b4027b%40googlegroups.com.