Commit 0e47bd16da

Andrew Kelley <andrew@ziglang.org>
2025-09-19 11:20:05
add behavior test: return undefined pointer from function
This clarifies that it is legal to return an invalid pointer from a function, provided that such pointer is not dereferenced. This matches current status quo of the language. Any change to this should be a proposal that argues for different semantics. It is also legal in C to return a pointer to a local. The C backend lowers such thing directly, so the corresponding warning in C must be disabled (`-Wno-return-stack-address`).
1 parent 4d1b15b
Changed files (2)
test
test/behavior/fn.zig
@@ -742,3 +742,30 @@ test "coerce generic function making generic parameter concrete" {
     const result = coerced({}, 123);
     try expect(result == 123);
 }
+
+test "return undefined pointer from function, directly and by expired local" {
+    const S = struct {
+        var global: i32 = 1;
+
+        fn returnGlobalPointer() *i32 {
+            return &global;
+        }
+
+        fn returnUndefPointer() *i32 {
+            return undefined;
+        }
+
+        /// Semantically equivalent to `returnUndefPointer`.
+        fn returnStackPointer() *i32 {
+            var stack_allocation: i32 = 1234;
+            return &stack_allocation;
+        }
+    };
+
+    const ok_ptr = S.returnGlobalPointer();
+    try expect(ok_ptr.* == 1);
+    const bad_ptr_1 = S.returnStackPointer();
+    _ = bad_ptr_1; // dereferencing this would be illegal behavior
+    const bad_ptr_2 = S.returnStackPointer();
+    _ = bad_ptr_2; // dereferencing this would be illegal behavior
+}
test/tests.zig
@@ -2385,6 +2385,11 @@ pub fn addModuleTests(b: *std.Build, options: ModuleTestOptions) *Step {
 
                     // https://github.com/llvm/llvm-project/issues/153314
                     "-Wno-unterminated-string-initialization",
+
+                    // In both Zig and C it is legal to return a pointer to a
+                    // local. The C backend lowers such thing directly, so the
+                    // corresponding warning in C must be disabled.
+                    "-Wno-return-stack-address",
                 },
             });
             compile_c.addIncludePath(b.path("lib")); // for zig.h