cguy
cguy

Reputation: 345

Golang memory allocation for string copy memory addresses

I am currently reading the Go Programming Language book which describes that a copy of a string or a substring has similar memory addresses.

s := "hello"
c := s

fmt.Println(&s, &c) // prints 0xc000010230 0xc000010240

My question is, shouldn't &c be the same as &s since it c is an exact copy ?

               RAM
      Address    |     Value
 &s 0xc000010230 |    "hello" <----- s
 &c 0xc000010240 |    "hello" <----- c

Upvotes: 2

Views: 858

Answers (1)

mkopriva
mkopriva

Reputation: 38213

c and s are actually two distinct string headers. But both of them point to the same "hello".

sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
ch := (*reflect.StringHeader)(unsafe.Pointer(&c))
fmt.Println(sh.Data, ch.Data)

https://go.dev/play/p/Ckl0P3g4nVo


The Data field of the string header points to the first byte in the string and the Len field of the string header indicates the length of the string. You can use that information to confirm that the string header is pointing to the original string.

sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
for i := 0; i < sh.Len; i++ {
    sp := (*byte)(unsafe.Pointer(sh.Data + uintptr(i)))
    fmt.Printf("%p = %c\n", sp, *sp)
}

https://go.dev/play/p/LFfdxxARw1f

Upvotes: 7

Related Questions