From 8c72fd5aea57ef65b4fed592ee7eaf86e1ec3661 Mon Sep 17 00:00:00 2001 From: Michal Dobrogost Date: Wed, 12 Nov 2025 12:45:47 -0500 Subject: [PATCH 1/2] std.mem.Allocator.alignedAlloc improve doc comment. --- lib/std/mem/Allocator.zig | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/std/mem/Allocator.zig b/lib/std/mem/Allocator.zig index 72581236e6df..cfa69d2932c6 100644 --- a/lib/std/mem/Allocator.zig +++ b/lib/std/mem/Allocator.zig @@ -248,6 +248,16 @@ pub fn allocSentinel( return self.allocWithOptionsRetAddr(Elem, n, null, sentinel, @returnAddress()); } +/// Allocates with an alignment which is incorporated into the returned type. +/// Call `free` when done. +/// +/// Prefer inferred types like `const data = alignedAlloc(...)` as it will use +/// the correctly aligned type. +/// +/// Avoid explicit types like `const data: u8[] = alignedAlloc(...)` as they +/// can change the alignment type information needed when calling `free`. +/// +/// If alignment is not comptime known use `rawAlloc` and `rawFree`. pub fn alignedAlloc( self: Allocator, comptime T: type, @@ -432,7 +442,7 @@ pub fn reallocAdvanced( return mem.bytesAsSlice(T, new_bytes); } -/// Free an array allocated with `alloc`. +/// Free an array allocated with `alloc` or `alignedAlloc`. /// If memory has length 0, free is a no-op. /// To free a single item, see `destroy`. pub fn free(self: Allocator, memory: anytype) void { From 7f9029ae321bc18a95f434948a79c5d6691bbe91 Mon Sep 17 00:00:00 2001 From: Michal Dobrogost Date: Fri, 14 Nov 2025 20:16:41 -0500 Subject: [PATCH 2/2] Update alignedAlloc doc comment. --- lib/std/mem/Allocator.zig | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/lib/std/mem/Allocator.zig b/lib/std/mem/Allocator.zig index cfa69d2932c6..ea1aea4ad02c 100644 --- a/lib/std/mem/Allocator.zig +++ b/lib/std/mem/Allocator.zig @@ -251,13 +251,22 @@ pub fn allocSentinel( /// Allocates with an alignment which is incorporated into the returned type. /// Call `free` when done. /// -/// Prefer inferred types like `const data = alignedAlloc(...)` as it will use -/// the correctly aligned type. +/// Assign to an inferred type to have a correctly specified alignment. +/// The alignment of the type will be used by `free` later. +/// Specifying a type may result in a silent coercion to a different alignment. /// -/// Avoid explicit types like `const data: u8[] = alignedAlloc(...)` as they -/// can change the alignment type information needed when calling `free`. +/// This is correct: +/// ``` +/// const data = alignedAlloc(...); +/// defer free(data); +/// const d: []u8 = data; +/// ``` /// -/// If alignment is not comptime known use `rawAlloc` and `rawFree`. +/// This is hazardous: +/// ``` +/// const d:[]u8 = alignedAlloc(...); +/// defer free(d); +/// ``` pub fn alignedAlloc( self: Allocator, comptime T: type,