* sheepbao <listome...@gmail.com> [180813 23:45]:
> go version
> go version go1.10.2 darwin/amd64
> 
> test code:
> 
> func TestPoint(t *testing.T) {
>     type A struct {
>         X int
>         Y string
>     }
>     type B struct {
>         X int
>         Y string
>         Z string
>     }
> 
>     a := A{X: 2, Y: "yy"}
>     b := (*B)(unsafe.Pointer(&a))
>     b.Z = "zz"
> 
>     fmt.Printf(" z: %v\n", b.Z)
>     return
> }

Enough bytes are allocated for a (of type A).  It doesn't matter whether
they are on the stack or on the heap.  Now you use unsafe to make b a
pointer to type B that points to the same memory location where a was
allocated.  The field Z of (*b) is beyond the memory that was allocated
on the heap or reserved on the stack for a.  Neither the compiler (for
stack-reserved a) nor the runtime (for heap-allocated a) has made any
provision for ensuring that the memory immediately beyond a is not used
for anything else.  Writing to b.Z overwrites memory to which b has no
claim.

Both this code and the change in your subsequent message are simply
wrong.  Whether it crashes or not depends on the legitimate "owner" of
the memory at b.Z.  If it is a return address on the stack, a crash is
almost certain.  If it is memory on the heap that has not been allocated
yet, and will never be allocated in such a simple program, you might not
see any evidence that the code was written incorrectly.

...Marvin

-- 
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