Skip to content

reflect: documentation about "Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer" is misleading #41705

Closed
@GingerMoon

Description

@GingerMoon

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.WaitingForInfoIssue is not actionable because of missing required information, which needs to be provided.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions