Shouldn't casting an object to void* be considered @safe?
Steven Schveighoffer
schveiguy at gmail.com
Mon Dec 16 17:10:05 UTC 2019
On 12/14/19 6:48 PM, Joseph Rushton Wakeling wrote:
> On Saturday, 14 December 2019 at 20:53:49 UTC, Dennis wrote:
>>> No, that won't do. What if you cast from a `ulong` to a `void*`?
>>
>> That is `@safe`, unless there is a way to corrupt memory in `@safe`
>> code by doing that.
>
> No, it is not @safe, and for good reason. When you cast an integral
> value to a `void*` that value gets reinterpreted as a memory address.
> But you have absolutely no right to assume that it is a valid memory
> address.
It's not technically unsafe, but is prone to safety problems. It's true
that a void * is completely unusable in safe code. But loads of code has
both safe and unsafe parts.
Not to mention that the GC makes different decisions based on whether a
type contains a pointer or not. I think we are reasonably fine leaving a
rule in place to prevent casting from a non reference type to a void *.
However, a class reference is very similar to a pointer, we should allow
that cast (to void * only).
>
> Things like this are WHY the spec has the rule that one cannot cast from
> a non-pointer type to `void*` in code marked @safe.
The spec rule is likely not focused on void * or classes, but really
something like:
auto p = cast(int*) 8;
which then can be used in safe code to do damage:
*p = 5;
-Steve
More information about the Digitalmars-d
mailing list