Safe cast of arrays

w0rp via Digitalmars-d digitalmars-d at puremagic.com
Wed Feb 10 00:49:21 PST 2016


On Tuesday, 9 February 2016 at 21:20:53 UTC, Iakh wrote:
> https://dlang.org/spec/function.html#function-safety
> Current definition of safety doesn't mention cast of arrays.
> E.g this code allowed by DMD
>
> int[] f(void[] a) @safe pure
> {
>     return cast(int[])a;
> }
>
> But same void* to int* cast is forbidden.
> So we need some rules for dynamic arrays casting.
> e.g allow only cast(void[]) as for pointers was done.
>
> And definition of safety should be changed.

I think this should be addressed, as if you can't cast between 
pointer types, you shouldn't be allowed to cast between slice 
types either. Because slices are just a pointer plus a length. 
Another way to demonstrate the problem is like this.

@safe
int* badCast(long[] slice) {
     return (cast(int[]) slice).ptr;
}


@system
void main(string[] argv) {
     auto larger = new long[5];
     auto smaller = badCast(larger);
}

This is a complete program which will compile and run with the 
latest official release of DMD. The pointer slicing is unsafe, 
but once the slice is available, it can go off into @safe land, 
and could lead to memory corruption, due to the bad cast. I used 
.ptr here to show you can safely take the pointer of a badly 
casted slice, which seems to somewhat contradict the rule that no 
pointer casting is allowed.

Maybe some exception is needed for casting slices of class types. 
That's about the only thing I can think of.


More information about the Digitalmars-d mailing list