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

unsafe.Offsetof() does not work properly in struct when struct is mixed of types int64 and byte #42846

Closed
tebrizetayi opened this issue Nov 26, 2020 · 4 comments

Comments

@tebrizetayi
Copy link

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

$ go version =1.15.5

Does this issue reproduce with the latest release?

Yes. I tried from playground.
https://play.golang.org/p/AMhf-IQDLF4

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

go env Output
$ go env
Linux amd64

What did you do?

I have struct that has int64 and byte type. When byte type variable is in the middle of other types in struct , the offset function does not show the proper offset(see link below)
https://play.golang.org/p/AMhf-IQDLF4

type custom struct {
a int64
b int64
c byte
d int64
e int64
f byte
g byte
}

the offset and address appropriately is

True 0 0xc000078030
True 8 0xc000078038
True 16 0xc000078040
False 24 0xc000078048 //But it should be 17 . 16+1 (a.c is byte type) =17
True 32 0xc000078050
True 40 0xc000078058
True 41 0xc000078059

What did you expect to see?

True 0 0xc0000a0000
True 8 0xc0000a0008
True 16 0xc0000a0010
True 17 0xc0000a0018
True 25 0xc0000a0020
True 33 0xc0000a0028
True 34 0xc0000a0029

What did you see instead?

True 0 0xc000078030
True 8 0xc000078038
True 16 0xc000078040
False 24 0xc000078048 //But it should be 17 . 16+1 (a.c is byte type) =17
True 32 0xc000078050
True 40 0xc000078058
True 41 0xc000078059

@tebrizetayi tebrizetayi changed the title unsafe.Offsetof() does not work properly in struct when struct is mixed of type unsafe.Offsetof() does not work properly in struct when struct is mixed of types int64 and byte Nov 26, 2020
@davecheney
Copy link
Contributor

Structs are padded to their natural alignment.

@tebrizetayi
Copy link
Author

Could you make it clear,please?

@davecheney
Copy link
Contributor

@martisch
Copy link
Contributor

As davecheney pointed out this is working as intended. Struct fields in Go gc implementation are not packed as close as possible but are aligned. See also https://golang.org/ref/spec#System_considerations. e.g. 64bit atomics might require the int64 to be properly aligned and some architectures might also require this as they do aligned loads.

See #36606 for a discussion of potentially allowing to specify packed struct layouts in the future.

@golang golang locked and limited conversation to collaborators Nov 26, 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

4 participants