On Tue, Aug 21, 2018 at 1:19 PM, 'Carl Mastrangelo' via golang-nuts
<golang-nuts@googlegroups.com> wrote:
>
> If I create an unsafe.Pointer that points to an invalid memory address, but
> I never deference it or otherwise pass it along, what happens to it?

If you never deference it and never do anything with it, then in
practice it most likely gets eliminated by the compiler.  That said:

> Is it a valid go program to just create such a pointer?

No.  The only way you could create such a Pointer is by converting
from uintptr, or, essentially equivalently, by calling C or assembler
code.  The unsafe package docs explain all the cases in which it is
permitted to convert a uintptr to an unsafe.Pointer.  Using any other
mechanism is invalid.  The permitted mechanisms never produce an
unsafe.Pointer that contains an invalid memory address.

> The main reason I ask is
> that I know the GC treats unsafe.Pointer values differently than uintptr.
> If the GC were to chase this invalid pointer, it would likely get a
> segfault.  This means that either the GC knows not to chase such a pointer,
> or it would chase it and gracefully recover.

In practice, in the current implementation, what will happen is that
the GC will attempt to find the object to which the pointer points,
will fail, and will crash with a "pointer to unallocated span" error.

> Additionally, if the unsafe.Pointer is pointing to a incorrectly aligned
> address, the GC could potentially misunderstand and try to walk it.  I'm
> sure this has been thought of before, but it isn't called out in the docs.

This isn't an issue with the current implementation.  The current GC
doesn't care about the type of the pointer, so pointers have no
alignment requirements as far as the GC is concerned.  Every pointer
is effectively a *byte for GC purposes.

Ian

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