r/Zig • u/YuvalAmir • 10d ago
Is this undefined behaviour?
Using ptrCast to get an unsigned pointer to a signed variable with a bitsize that's not a power of 2 shows nonsensical data.
Reproducible example (in debug):
const std = @import("std");
test "reading an i30 through a u30 pointer" {
var x: i30 = -1;
const view: *u30 = @ptrCast(&x);
std.debug.print("bytes of x: {x}\n", .{std.mem.asBytes(&x)});
try std.testing.expectEqual(std.math.maxInt(u30), view.*);
}
output:
bytes of x: ffffffff
expected 1073741823, found 4294967295Somehow view.* is larger than the maximum value u30 should be able to hold. It is actually the u32 max value.
edit: I tried using an LLM to investigate this and the cause is actually very interesting.
The issue has to do with the padding bits. A signed write to a bit size with padding bits sets every padding bit to the sign bit. That's the case because it makes reads into something like an i30 very simple, you just load the four bytes and read them like you would an i32 without any adjustments (in two's complement negative numbers essentially count "down" from negative one which is 111..111 so adding additional 1 bits to a negative number is the same as adding additional 0 bits to a positive number).
Unsigned writes always write 0 into the padding bits for the same reason, it lets you read the full bytes with no masking and get the same values.
The problem is that this mechanism breaks when the type that was assumed when writing into memory isn't the one that's assumed when reading from it. The padding bits still don't get masked out and you get 32 bit data that doesn't make sense for 30 logical bits.
This edit is mainly me trying to explain this to myself. Sorry if the terminology is wrong, I don't have any formal CS education (though I should be starting my CS degree at October of next year).
10
u/johan__A 10d ago edited 9d ago
this might be a bug with the self hosted backend, you can try -fllvm to force the llvm backend. I think it would not be undefined behaviour but the language doesn’t have a complete specification document yet so I cant say for sure.
0
u/TheSodesa 9d ago
You cannot have undefined behaviour if your language does not have a standard.