Skip to content

Coercion to less aligned is not safe #25908

@michal-dobrogost

Description

@michal-dobrogost

Zig Version

0.15.2

Steps to Reproduce and Observed Behavior

Coercing a more aligned type to a less aligned type is not safe as the memory is no longer able to be freed correctly. This coercion behaviour disables std.mem.alignedAlloc from enforcing that the returned type has the correct alignment (or flagging the risky behaviour via @alignCast).

This has hit multiple users (+1 for myself now) and is only detected by std.testing.allocator. Other allocators continue silently.
https://discordapp.com/channels/605571803288698900/1375373321691992126
https://discordapp.com/channels/605571803288698900/1421631270504632441

Repro:

test "alignedAlloc" {
    const gpa = std.testing.allocator;
    const alignment: std.mem.Alignment = @enumFromInt(4);
    const data: []u8 = try gpa.alignedAlloc(u8, alignment, 12);
    defer gpa.free(data); // [gpa] (err): Allocation alignment 16 does not match free alignment 1.
}

Expected Behavior

Any change in alignment requires @alignCast.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions