Skip to content

Commit f9cf539

Browse files
authored
[libc][malloc] Align blocks to max_align_t. (#100279)
Since there are two offsets from block start to usable area, this ensures that the usable area is maximally aligned, so long as the offset type size is no less than half the max alignment. This is true on at least typical 32-bit and 64-bit targets. Previously, there was a roughly 50-50 chance a given block's usable area would be misaligned for a malloc on a 32-bit system. The half that were misaligned would require at least one block of additional padding, costing 12 bytes. With this change, the only cost is 0-4 bytes at the beginning of the heap to reach an initial 8-byte alignment. See #98096
1 parent f3f0d99 commit f9cf539

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

libc/src/__support/block.h

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,12 @@ using cpp::optional;
102102
/// types can address more memory, but consume greater
103103
/// overhead.
104104
/// @tparam kAlign Sets the overall alignment for blocks. Minimum is
105-
/// `alignof(OffsetType)` (the default). Larger values
106-
/// cause greater overhead.
107-
template <typename OffsetType = uintptr_t, size_t kAlign = alignof(OffsetType)>
105+
/// `alignof(OffsetType)`, but the default is max_align_t,
106+
/// since the usable space will then already be
107+
/// aligned to max_align_t if the size of OffsetType is no
108+
/// less than half of max_align_t. Larger values cause
109+
/// greater overhead.
110+
template <typename OffsetType = uintptr_t, size_t kAlign = alignof(max_align_t)>
108111
class Block {
109112
// Masks for the contents of the next_ field.
110113
static constexpr size_t USED_MASK = 1 << 0;

0 commit comments

Comments
 (0)