From 0e47bd16dac9dcdfc12168c07104030af8eaaa8b Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 19 Sep 2025 02:20:05 -0700 Subject: [PATCH] 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`). --- test/behavior/fn.zig | 27 +++++++++++++++++++++++++++ test/tests.zig | 5 +++++ 2 files changed, 32 insertions(+) diff --git a/test/behavior/fn.zig b/test/behavior/fn.zig index ceae020bb8..945d0fb3ca 100644 --- a/test/behavior/fn.zig +++ b/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 +} diff --git a/test/tests.zig b/test/tests.zig index 8bcdce7aad..f4c5e01ac8 100644 --- a/test/tests.zig +++ b/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