Hey, I work a lot with WASM and have been jumping into Zig, but I’ve noticed that pointers are assumed to be non-zero, and an optional pointer will be represented as zero.
There’s nothing really suggesting that 0 is an invalid pointer, sure, most programs handle it that way due to all (major?) OSes treating it that way, but in WASM, and presumably in other environments, 0 is a valid pointer, and I’m wondering how Zig handles this.
I’m no expert in this area but maybe this section of the language reference can shed a little light? (It’s about the allowzero
keyword)
Yes, also saw that and it’s essentially what I’d expect be the default during compilation, but I can find no mention of WASM compilation causing all pointers being allowzero
. (And it’d have it’s own issues, ie optional allowzero pointers are not the same size as normal pointers).
Additionally, the WASM allocator does not return allowzero pointers, so I’d think it’s handled differently
I don’t know how Zig does it, but at least in C, I’ve heard that null pointers are technically allowed to have any value in the compiled code, as long as the whole thing is transparent to non-UB source code. So char *ptr = 0;
could end up having an ABI-defined value in machine code, not 0.
Most operating systems can catch null pointer dereferences in userspace by mapping the process’ memory space’s 0th page in a way that causes memory protection interrupts when read or written (idk the exact details).