ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.82k stars 2.47k forks source link

`@ptrCast` provides no safety guarantee for casts to `[*]T` from`?[]T` at runtime #21302

Open amp-59 opened 2 weeks ago

amp-59 commented 2 weeks ago

Zig Version

0.14.0-dev.1411+a670f5519

Steps to Reproduce and Observed Behavior

Compile and run example program with zig run ptrcast_opt_slice_to_manyptr_error.zig ptrcast_opt_slice_to_manyptr_error.zig:

pub fn main() void {
    var x: ?[]u8 = &.{};
    var y: [*]u8 = undefined;

    x = null;

    y = @ptrCast(x);

    if (@intFromPtr(y) == 0) {
        @import("std").debug.print("value is zero\n", .{});
    }
}

Output:

zig run ptrcast_opt_slice_to_manyptr_error.zig
value is zero

Expected Behavior

The program above should panic at runtime with panic ID cast_to_null.

Running an equivalent program at compile time will yield the expected outcome.

Compile example program with zig build-obj ptrcast_opt_slice_to_manyptr_comptime.zig ptrcast_opt_slice_to_manyptr_comptime.zig:

comptime {
    var x: ?[]u8 = &.{};
    var y: [*]u8 = undefined;

    x = null;
    y = @ptrCast(x);
}

Output:

zig build-obj ptrcast_opt_slice_to_manyptr_comptime.zig
ptrcast_opt_slice_to_manyptr_comptime.zig:6:18: error: null pointer casted to type '[*]u8'
    y = @ptrCast(x);
                 ^
notcancername commented 1 week ago

Should @ptrCast even be allowed in this case? Wouldn't .?.ptr be more explicit?