From 4b5fc5239c37fa3f49965188256a781c7b1277a3 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 29 Dec 2022 20:25:40 -0700 Subject: [PATCH] std.heap.raw_c_allocator: fix illegal alignment cast See the comment added in this commit for more details. closes #14090 --- lib/std/heap.zig | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/std/heap.zig b/lib/std/heap.zig index 081e65fa27..9c0abc62a6 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -181,9 +181,13 @@ fn rawCAlloc( ) ?[*]u8 { _ = ret_addr; assert(log2_ptr_align <= comptime std.math.log2_int(usize, @alignOf(std.c.max_align_t))); - // TODO: change the language to make @ptrCast also do alignment cast - const ptr = @alignCast(@alignOf(std.c.max_align_t), c.malloc(len)); - return @ptrCast(?[*]align(@alignOf(std.c.max_align_t)) u8, ptr); + // Note that this pointer cannot be aligncasted to max_align_t because if + // len is < max_align_t then the alignment can be smaller. For example, if + // max_align_t is 16, but the user requests 8 bytes, there is no built-in + // type in C that is size 8 and has 16 byte alignment, so the alignment may + // be 8 bytes rather than 16. Similarly if only 1 byte is requested, malloc + // is allowed to return a 1-byte aligned pointer. + return @ptrCast(?[*]u8, c.malloc(len)); } fn rawCResize(