Skip to content

memset/memcpy comptime error: out of bounds pointer access #4718

@mikdusan

Description

@mikdusan
export fn fail_memset() void {
    comptime {
        var num: u32 = undefined;
        @memset(@ptrCast([*]u8, &num), 0, @sizeOf(u32));
    }
}

export fn fail_memcpy() void {
    comptime {
        var src: u32 = 99;
        var dst: u32 = undefined;
        @memcpy(@ptrCast([*]u8, &dst), @ptrCast([*]const u8, &src), @sizeOf(u32));
    }
}
./bug1.zig:4:43: error: out of bounds pointer access
        @memset(@ptrCast([*]u8, &num), 0, @sizeOf(u32));
                                          ^
./bug1.zig:4:9: note: referenced here
        @memset(@ptrCast([*]u8, &num), 0, @sizeOf(u32));
        ^
./bug1.zig:12:9: error: out of bounds pointer access
        @memcpy(@ptrCast([*]u8, &dst), @ptrCast([*]const u8, &src), @sizeOf(u32));
        ^

This was found by trying:

const Foo = extern struct {
    num: u32,
};

var x: [*:comptime std.mem.zeroes(Foo)]Foo = undefined;
// or
_ = comptime std.mem.zeroes(Foo);

std.mem exposure with zeroes and secureZero (and probably more) can be worked around by replacing the builtins { @memset, @memcpy } with { std.mem.set, std.mem.copy } respectively but is not a solve for the primary issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions