Closed
Description
The document about "Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer" is misleading.
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1
hdr.Data = uintptr(unsafe.Pointer(p)) // case 6 (this case)
hdr.Len = n
It would be great if the doc specifies one more time the risk of the code below:
hdr.Data = uintptr(unsafe.Pointer(p))
When p point to a temporary memory, we will have problem. For example,
func demo(val_copy int64) *reflect.StringHeader {
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1
hdr.Data = uintptr(unsafe.Pointer(&val_copy)) // case 6 (this case)
hdr.Len = 8
return hdr
}
func main() {
val := int64(0xab)
hdr := demo(val)
s := *(*string)(unsafe.Pointer(hdr))
fmt.Printf("%x", s)
}
The tricky thing is, it's often that the output is the same as expectation.
But this is a bug because &val_copy is not referenced by others except uintptr, hence the content of the memory pointed by &val_copy is undefined after the demo function returned.