Shouldn't casting an object to void* be considered @safe?
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Sun Dec 15 09:15:39 UTC 2019
On Sunday, 15 December 2019 at 07:40:41 UTC, Ola Fosheim Grøstad
wrote:
> On Saturday, 14 December 2019 at 23:48:38 UTC, Joseph Rushton
> Wakeling wrote:
>> ulong u = 8;
>> auto v = cast(void*) u;
>>
>> ... is totally unsafe, and the compiler rightly rejects it if
>> you try to do that in a code block marked @safe.
>
> It is not type safe, but it is memory safe.
>
> void has zero extent, so it will never be dereferenced without
> an unsafe action.
Which brings us back to the start of the discussion: @safe checks
are not just about the strictest definition of memory safety, but
also about actions that open up a path to unsafe behaviour unless
they are carefully validated.
You may not accept the principle but that is the reality of the
spec.
> It is no different from having a pointer to a zero-length
> array, or a zero-length slice. Allocators will often allocate 1
> byte if asked to allocate 0 though, to avoid such typing
> issues. I.e. to allow you to obtain unique identities with zero
> extent.
I'm not sure that's true. The pointer of a zero-length array
should be guaranteed to be `null` or to point to a valid section
of GC memory. An arbitrary integral value reinterpreted as a
memory address has no such guarantee.
BTW, note that the array/slice `.ptr` property is not @safe,
precisely because it opens the door to looking into a buffer of
memory that one is not supposed to have access to.
> So it is problematic, but not because of void*. It is only
> problematic because other code is unsafe.
These are not the criteria that @safe operates by. But FWIW in
these cases you're right that there's nothing magical about
`void*`. It's the casting of a non-pointer type to ANY pointer
type that is considered a violation of @safe.
More information about the Digitalmars-d
mailing list