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`).
This commit is contained in:
Andrew Kelley 2025-09-19 02:20:05 -07:00
parent 4d1b15bd9d
commit 0e47bd16da
2 changed files with 32 additions and 0 deletions

View file

@ -742,3 +742,30 @@ test "coerce generic function making generic parameter concrete" {
const result = coerced({}, 123); const result = coerced({}, 123);
try expect(result == 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
}

View file

@ -2385,6 +2385,11 @@ pub fn addModuleTests(b: *std.Build, options: ModuleTestOptions) *Step {
// https://github.com/llvm/llvm-project/issues/153314 // https://github.com/llvm/llvm-project/issues/153314
"-Wno-unterminated-string-initialization", "-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 compile_c.addIncludePath(b.path("lib")); // for zig.h