I recently came across http://golang-sizeof.tips/ which explains how the memory is allocated for a struct. I get it that to ensure contiguous memory allocation, we add padding when allocating memory for variables which without padding will not get contiguous memory. So i was testing out various combinations on my 64-bit computer, and found a mismatch between the results on the site and my computer. It was for this case:
type S2 struct {
a string
b bool
e bool
d int32
f bool
c string
}
In the main, the following code gives me 48
as the size of the variable.
y := S2{"q", true, true,2,true,"w"}
fmt.Println(unsafe.Sizeof(y))
But this is different from what its supposed to be as per http://golang-sizeof.tips/?t=blahblah. Why is this kind of behaviour observed? (I hope this is not some problem with my computer alone). Edit: Logically speaking padding is not necessary in between fields d
and f
I also ran the following code just to make sure.
fmt.Println(unsafe.Offsetof(y.a))
fmt.Println(unsafe.Offsetof(y.b))
fmt.Println(unsafe.Offsetof(y.e))
fmt.Println(unsafe.Offsetof(y.d))
fmt.Println(unsafe.Offsetof(y.f))
fmt.Println(unsafe.Offsetof(y.c))
Result:
0
16
17
20
24
32
play.golang.org uses 32-bit machine, so i doubt that the same can be reproduced there!
Your calculation of 48 bytes is correct for amd64.
package main
import (
"fmt"
"unsafe"
)
type S2 struct { // align 16
a string // size 16 = 8 + 8
b bool // size 1
e bool // size 1
// pad size 2
d int32 // size 4
f bool // size 1
// pad size 7
c string // size 16 = 8 + 8
}
func main() {
y := S2{}
fmt.Println(unsafe.Sizeof(y))
fmt.Println(unsafe.Offsetof(y.a))
fmt.Println(unsafe.Offsetof(y.b))
fmt.Println(unsafe.Offsetof(y.e))
fmt.Println(unsafe.Offsetof(y.d))
fmt.Println(unsafe.Offsetof(y.f))
fmt.Println(unsafe.Offsetof(y.c))
fmt.Println(&y.a)
fmt.Println(&y.b)
fmt.Println(&y.e)
fmt.Println(&y.d)
fmt.Println(&y.f)
fmt.Println(&y.c)
}
Output:
48
0
16
17
20
24
32
0xc000070150
0xc000070160
0xc000070161
0xc000070164
0xc000070168
0xc000070170
The Go Programming Language Specification : Size and alignment guarantees