Do slice element modification operations check whether or not the modified elements are allocated on immutable zones?

77 views
Skip to first unread message

T L

unread,
Jan 16, 2020, 8:27:34 AM1/16/20
to golang-dev
It looks the following program shows this is true. But is it really?

package main

import (
	"fmt"
	"strings"
	"unsafe"
)
var _ = strings.Join

type SliceHeader struct {
	Data unsafe.Pointer
	Len  int
	Cap  int
}

type StringHeader struct {
	Data unsafe.Pointer
	Len  int
}

func String2ByteSlice(str string) (bs []byte) {
	strHdr := (*StringHeader)(unsafe.Pointer(&str))
	sliceHdr := (*SliceHeader)(unsafe.Pointer(&bs))
	sliceHdr.Data = strHdr.Data
	sliceHdr.Len = strHdr.Len
	sliceHdr.Cap = strHdr.Len

	return
}

//var Golang = strings.Join([]string{"Go", "lang"}, "") // not cause panicking
var Golang = "Golang"                                   // causes panicking

func main() {
	var goland = String2ByteSlice(Golang)
	goland[5] = 'd' // fatal error: unexpected fault address
	fmt.Printf("%s\n", goland)
}

Ralph Corderoy

unread,
Jan 16, 2020, 8:35:28 AM1/16/20
to T L, golan...@googlegroups.com
Hi Tapir,

> Do slice element modification operations check whether or not the
> modified elements are allocated on immutable zones?
...
> //var Golang = strings.Join([]string{"Go", "lang"}, "") // not cause panicking
> var Golang = "Golang" // causes panicking

Are you aware that memory pages may have permissions such as read-only,
and that some data may be allocated to those pages? Look up the address
of the data in /proc/$pid/maps.

I think this topic belongs on golang-nuts; reply-to set.

--
Cheers, Ralph.

T L

unread,
Jan 16, 2020, 9:49:11 AM1/16/20
to golang-nuts, golang-dev
Glad to know this. Thanks for the info.
Reply all
Reply to author
Forward
0 new messages