Skip to content

Commit e218b7e

Browse files
InKryptionandrewrk
authored andcommitted
stage2: add compile error for invalid null/undefined pointer cast
1 parent 0e118ed commit e218b7e

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Sema.zig

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17272,6 +17272,15 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1727217272
else
1727317273
operand;
1727417274

17275+
if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| {
17276+
if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) {
17277+
return sema.failWithUseOfUndef(block, operand_src);
17278+
}
17279+
if (!dest_ty.ptrAllowsZero() and operand_val.isNull()) {
17280+
return sema.fail(block, operand_src, "null pointer casted to type {}", .{dest_ty.fmt(sema.mod)});
17281+
}
17282+
}
17283+
1727517284
const dest_elem_ty = dest_ty.elemType2();
1727617285
try sema.resolveTypeLayout(block, dest_ty_src, dest_elem_ty);
1727717286
const dest_align = dest_ty.ptrAlignment(target);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
comptime {
2+
var opt_ptr: ?*i32 = null;
3+
const ptr = @ptrCast(*i32, opt_ptr);
4+
_ = ptr;
5+
}
6+
7+
// error
8+
// backend=llvm
9+
// target=native
10+
//
11+
// :3:32: error: null pointer casted to type *i32
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
comptime {
2+
var undef_ptr: *i32 = undefined;
3+
const ptr = @ptrCast(*i32, undef_ptr);
4+
_ = ptr;
5+
}
6+
7+
// error
8+
// backend=llvm
9+
// target=native
10+
//
11+
// :3:32: error: use of undefined value here causes undefined behavior

0 commit comments

Comments
 (0)