zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 0e47bd16dac9dcdfc12168c07104030af8eaaa8b (tree)
parent 4d1b15bd9d4175127a63595f4fd80761c2e6564c
Author: Andrew Kelley <andrew@ziglang.org>
Date:   Fri, 19 Sep 2025 02:20:05 -0700

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`).

Diffstat:
Mtest/behavior/fn.zig | 27+++++++++++++++++++++++++++
Mtest/tests.zig | 5+++++
2 files changed, 32 insertions(+), 0 deletions(-)

diff --git 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 @@ -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