zig icon indicating copy to clipboard operation
zig copied to clipboard

Pointer difference expected to have @divExact semantics

Open vadim-za opened this issue 7 months ago • 1 comments

Zig Version

0.14.0

Steps to Reproduce and Observed Behavior

Compile a debug build of and run the following code:

const std = @import("std");

pub fn main() void {
    const S = extern struct { x: i32, y: i32 };
    const a: [10]S = undefined;
    var p = &a[2];
    const p1 = &a[5];

    // Make p point midway between a[1] and a[2]
    p = @ptrFromInt(@intFromPtr(p) - 4);

    // Expected implementation:
    // const d = @divExact(@intFromPtr(p1) - @intFromPtr(p), @sizeOf(S));
    // Actual implementation:
    // const d = @intFromPtr(p1) - @intFromPtr(p)) / @sizeOf(S);
    // Expected result: runtime panic
    // Actual result: d = 3
    const d = p1 - p;
    std.debug.print("{}\n", .{d});
}

The code prints the value 3

Expected Behavior

The code runtime-panics in safe builds

vadim-za avatar Apr 03 '25 15:04 vadim-za

I'm not sure if this is a miscompilation or if the feature is implemented as specified and we need a proposal to change it. @mlugg do you know?

alexrp avatar May 28 '25 13:05 alexrp