Skip to content

Null pointer optimization when the pointer is in a structure #24212

Closed as duplicate of#104
@wooster0

Description

@wooster0
comptime {
    @compileLog(@sizeOf(?*u8));
}
Compile Log Output:
@as(comptime_int, 8)

Because this pointer doesn't have the allowzero attribute it, as expected, Zig uses address zero for null.

However when you do this:

const Thing = struct {
    pointer: *u8,
};

comptime {
    @compileLog(@sizeOf(?Thing));
}
Compile Log Output:
@as(comptime_int, 16)

That doesn't apply anymore.

Additionally, in more complicated cases like this:

const Thing = struct {
    hello: u64,
    world: enum { a, b, c },
    pointer: *u8,
};

comptime {
    @compileLog(@sizeOf(?Thing));
}

It should be able to figure out that it can use any pointer's zero address within the structure to represent null for ?Thing. That would make the size shrink to 24 bytes from 32 currently.
This could be combined with #168 to move non-allowzero pointers to the top so it can perhaps check for null a bit faster? I don't know.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions