Casting arrays
solidstate1991
laszloszeremi at outlook.com
Thu May 30 14:37:51 UTC 2019
On Thursday, 30 May 2019 at 08:30:14 UTC, Dennis wrote:
> Don't do this, that function can not be trusted. For casts of
> basic types, the compiler already has such runtime checks:
>
> ```
> int[] a = [3, 4, 5];
> auto b = cast(double[]) a;
> ```
>
> "An array of size 12 does not align on an array of size 8, so
> `int` cannot be cast to `double`"
>
> You allowing it for ANY type as long as alignment is okay
> invites all kinds of safety violations.
>
> ```
> void main() @safe
> {
> char*[1] a = [new char('\xCC')];
> auto slice = a[];
> auto b = reinterpretCast!(int*)(slice);
> writefln("%08X", *b[0]);
> }
> ```
> https://run.dlang.io/is/QVNlEv
>
> Prints:
> 743B50CC
>
> The 74 3B 50 are bytes out of bounds. There's more to array
> casting than alignment for it to be safe.
I know. I probably should upgrade the wrapper to filter out
pointer arrays, structs with pointers (or arrays) in them are
also an interesting question. I mainly use it for fast loading of
structs from files rather than painstakingly load each individual
value, also this way I just can put the read or writebuffer to
the checksum calculator, so pointers weren't really an issue for
me.
More information about the Digitalmars-d
mailing list