From ac58eca0156efe17135fbe503978219a963621ea Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 25 Apr 2023 03:40:01 +0530 Subject: [PATCH] checker: disallow deferencing a `nil` pointer (#18038) --- vlib/v/checker/checker.v | 9 +++++++++ vlib/v/checker/tests/deference_nil_ptr_err.out | 5 +++++ vlib/v/checker/tests/deference_nil_ptr_err.vv | 3 +++ 3 files changed, 17 insertions(+) create mode 100644 vlib/v/checker/tests/deference_nil_ptr_err.out create mode 100644 vlib/v/checker/tests/deference_nil_ptr_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 012b9d1304..a971949940 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3876,6 +3876,15 @@ fn (mut c Checker) prefix_expr(mut node ast.PrefixExpr) ast.Type { if right_type.is_voidptr() { c.error('cannot dereference to void', node.pos) } + if mut node.right is ast.Ident { + if var := node.right.scope.find_var('${node.right.name}') { + if var.expr is ast.UnsafeExpr { + if var.expr.expr is ast.Nil { + c.error('cannot deference a `nil` pointer', node.right.pos) + } + } + } + } } if node.op == .bit_not && !c.unwrap_generic(right_type).is_int() && !c.pref.translated && !c.file.is_translated { diff --git a/vlib/v/checker/tests/deference_nil_ptr_err.out b/vlib/v/checker/tests/deference_nil_ptr_err.out new file mode 100644 index 0000000000..a52cfc9823 --- /dev/null +++ b/vlib/v/checker/tests/deference_nil_ptr_err.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/deference_nil_ptr_err.vv:3:10: error: cannot deference a `nil` pointer + 1 | foo_ptr := unsafe { nil } + 2 | + 3 | println(*foo_ptr) + | ~~~~~~~ diff --git a/vlib/v/checker/tests/deference_nil_ptr_err.vv b/vlib/v/checker/tests/deference_nil_ptr_err.vv new file mode 100644 index 0000000000..55b6f30dab --- /dev/null +++ b/vlib/v/checker/tests/deference_nil_ptr_err.vv @@ -0,0 +1,3 @@ +foo_ptr := unsafe { nil } + +println(*foo_ptr)