On Sunday, February 25, 2018 at 10:01:44 AM UTC-5, Jan Mercl wrote:
>
>
> On Sun, Feb 25, 2018 at 3:20 PM <di...@veryhaha.com <javascript:>> wrote:
>
> > I think the unsafe rules allow this.
>
> Yes, but using unsafe provides no guarantees about writable memory.
>
> > I never expect it will crash, for I can't get any information about the 
> write protection mechanism.
>
> That's not part of the memory model and most probably never will. Layout 
> and/or protection of the sections is the design choice of the compiler 
> writer. But text constants are put in a R/O segment by many, if not most 
> AOT compilers.
>
>
I think I get it.
Because the above program tries to modify the constant (or program) zone, 
which is not allowed.
The following program works:

package main

import "fmt"
import "unsafe"
import "reflect"

func main() {
    s := string([]byte{'k', 'e', 'e', 'p'})
    hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
    byteSequence := (*byte)(unsafe.Pointer(hdr.Data))
    fmt.Println(string(*byteSequence)) // k
    *byteSequence = 'j' // crash here
    fmt.Println(s) // expect: jeep
}
 

>
> -- 
>
> -j
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to