Is assigning `&.{}` to a slice valid(memory safe)?

const std = @import("std");

pub fn main() void {
    const a: []u8 = &.{};
    const b: []i32 = &.{};
    std.debug.print("{x}\n", .{@intFromPtr(a.ptr)});
    std.debug.print("{x}\n", .{@intFromPtr(b.ptr)});
    std.debug.print("{x}\n", .{@intFromPtr(&.{})});
}

The above code compiles without an error and prints this:

aaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaa

Seems like &.{} is always aaaaaaaaaaaaaaaa even if it’s compiled with ReleaseFast.

Is it ok to assign &.{} to a slice?

It is valid. You could think of const a: []u8 = &.{}; being the same as:

var a: []u8 = undefined;
a.len = 0;

The compiler writes 0xaa bytes to undefined memory, although it’s not guaranteed to be always observable to code, see the undefined langref section.

4 Likes