Commit 4b5fc5239c

Andrew Kelley <andrew@ziglang.org>
2022-12-30 04:25:40
std.heap.raw_c_allocator: fix illegal alignment cast
See the comment added in this commit for more details. closes #14090
1 parent 40ba4d4
Changed files (1)
lib
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(