@@ -268,20 +268,28 @@ class Block {
268
268
if (alignment == alignof (max_align_t ))
269
269
return size;
270
270
271
- // We must create a padding block to align the usable space of the next
272
- // block. The next block's usable space can be found by advancing by
273
- // sizeof(Block) then aligning up. The amount advanced is the amount of
274
- // additional inner size required.
275
- //
276
- // The minimum advancment is sizeof(Block), since the resulting position may
277
- // happen to be aligned. What is the maximum? Advancing by sizeof(Block)
278
- // leaves the result still aligned to alignof(Block). So the most additional
279
- // advancement required would be if the point is exactly alignof(Block) past
280
- // alignment. The remaining size to the next alignment would then be
281
- // alignment - alignof(Block). So the total maximum advancement required is
282
- // sizeof(Block) + alignment - alignof(Block).
271
+ // We must create a new block inside this one (splitting). This requires a
272
+ // block header in addition to the requested size.
283
273
if (add_overflow (size, sizeof (Block), size))
284
274
return 0 ;
275
+
276
+ // Beyond that, padding space may need to remain in this block to ensure
277
+ // that the usable space of the next block is aligned.
278
+ //
279
+ // Consider a position P of some lesser alignment, L, with maximal distance
280
+ // to the next position of some greater alignment, G, where G is a multiple
281
+ // of L. P must be one L unit past a G-aligned point. If it were one L-unit
282
+ // earlier, its distance would be zero. If it were one L-unit later, its
283
+ // distance would not be maximal. If it were not some integral number of L
284
+ // units away, it would not be L-aligned.
285
+ //
286
+ // So the maximum distance would be G - L. As a special case, if L is 1
287
+ // (unaligned), the max distance is G - 1.
288
+ //
289
+ // This block's usable space is aligned to max_align_t >= Block. With zero
290
+ // padding, the next block's usable space is sizeof(Block) past it, which is
291
+ // a point aligned to Block. Thus the max padding needed is alignment -
292
+ // alignof(Block).
285
293
if (add_overflow (size, alignment - alignof (Block), size))
286
294
return 0 ;
287
295
return size;
0 commit comments