Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doubt about behaviour of unsafe.Pointer when converting string to int32 #42046

Closed
andreleoni opened this issue Oct 18, 2020 · 2 comments
Closed

Comments

@andreleoni
Copy link

What version of Go are you using (go version)?

PS C:\Users\cliente\Desktop\gostudies> go version
go version go1.15.3 windows/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

go env Output
$ go env

What did you do?

I'm studying about the unsafe.Pointer when working with pointers.

I looked that the unsafe.Pointer should return a float, or an int into another format, for example:

If I have an int64 variable pointer, I should transform into int32 by the (*int32)(unsafe.Pointer(t.value)) usage.

package main

import (
	"fmt"
	"unsafe"
)

type test struct {
	value *int64
}

func main() {
	var v int64
	v = 123
	t := test{&v}

	var ptest = (*int32)(unsafe.Pointer(t.value))
	fmt.Println(ptest)
	fmt.Println(*ptest + 10)
}

This is good behavior.

So, I tried to change the int32 of the unsafe.Pointer to string like this function:

package main

import (
	"fmt"
	"unsafe"
)

type test struct {
	value *string
}

func main() {
	var v string
	v = "123"
	t := test{&v}

	var ptest = (*int32)(unsafe.Pointer(t.value))
	fmt.Println(ptest)
	fmt.Println(*ptest + 10)
}

When I did it, I am getting the following response from execution:

PS C:\Users\cliente\Desktop\gostudies> go run main.go
0xc00004a1f0
17736171

What did you expect to see?

I expected to convert my "123" to 123 integer to sum with my 10 number.

What did you see instead?

This number 17736171 is a "random" number.

What does the 17736171 meaning in this case?

@davecheney
Copy link
Contributor

A string is a two work structure, a pointer to the character array holding the string data and a length field. 17736171 Is likely the address of the first character in the underlying array.

Thank you for raising this issue. Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

For asking questions, see:

@andreleoni
Copy link
Author

thank you for the fast answer, I will use the Go forum for this type of doubt!

@golang golang locked and limited conversation to collaborators Oct 18, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants