-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
design flaw: undefined zig pointers: are they non-null or not? #3325
Comments
Slices are also affected by this. Following code causes segmentation fault at runtime instead of an out-of-bounds panic in debug mode: fn foo(slice: []u8) void {
const x = slice[0];
_ = x;
}
pub fn main() void {
var slice: []u8 = undefined;
foo(slice);
} I guess, in general, |
Not sure if this could be related but following code leads to seg fault with undefined pointer. Just exploring zig.
The output |
yes that segfault is expected given your code |
is there a use case where having an undefined pointer ever makes sense? could assigning undefined to a pointer be make a compile error? (sure there would be ways to trick it but it would make that it is illegal behavior a lot more obvious) |
Generally speaking I think the way a pointer becomes undefined is most frequently as a field of a struct in an allocated slice, ie |
This issue is not related to allowzero.
A Zig pointer, such as
*i32
or[*]u8
, is guaranteed to be non-null. Optional pointers must be used to gainnull
as a possible value:?*i32
or?[*]u8
. So we put thenonnull
LLVM attribute on functions. However, that makes this simple Zig code undefined behavior, even in debug mode:Because
not_even_used
isundefined
, that means it could be0
which violates thenonnull
attribute. This could be solved by not puttingnonnull
attribute on pointer parameters, though it would be unfortunate since most of the timenonnull
is correct.It's also a question of whether to put
nonnull
on loads, stores, and other places having to do with Zig pointers.The more I think about it, the more I think the answer is that Zig pointers have a slightly different property than
nonnull
. The property isnonnull_or_undefined
. This is not an LLVM concept that currently exists, but I have a gut instinct that it should. Any time that thenonnull
attribute would allow the optimizer to do anything useful, if the value werenonnull_or_undefined
it should allow the optimizer to do the same thing. The only issue is thatundefined
is violatingnonnull
.Related:
undefined
(audit analysis of undefined values; make it clear when undefined is allowed or not #1947)I promise that the above Zig code snippet will not make it into the 1.0 language specification (#75) as undefined behavior. This will be resolved some way or another.
The text was updated successfully, but these errors were encountered: