Align First, Then Reuse Capacity

Work aligned allocation before splitting, coalescing, and diagnostics. Each exercise changes a different part of the byte layout.

1 / 9

Trace the aligned payload

Raw address 1000, pointer size 8, alignment 64, request 20. Reserve 20+63+8=91 bytes. Start at 1008; align to 1024. Saved pointer: [1016,1024). User payload: [1024,1044). Paired free recovers 1000; the interior address is not a separate allocation.

2 / 9

Check both arithmetic boundaries

Check padding and saved-pointer additions before allocating. The base allocator also checks rounding, header addition, and signed growth. Toy maximum 255: size 240 + padding 15 fits, but the 8-byte slot does not. Reject without consuming a free block or changing a live allocation.

3 / 9

Account for the new header

Capacity 120, header 24, alignment 8, request 33.

Round request to 40. What usable payload remains after splitting?

4 / 9

Reverse the arithmetic

120 - 40 - 24 = 56.

Merging the neighbors later gives 40 + 24 + 56 = 120.

The second header occupies bytes that used to be payload.

5 / 9

Split threshold

Minimum remainder payload 16: require capacity - aligned_request >= 24 + 16.

First check the request fits. Capacity 72 and aligned request 40 leave 32: no split.

6 / 9

Alignment has an owner

Reserve padding and an original-pointer slot. Return an aligned interior pointer.

Paired free retrieves and frees the original allocation. Do not free the interior address directly.

7 / 9

Merge only if both blocks are free and A + header + A.capacity == B.

Skipping over a live block would hand its storage to another allocation.

8 / 9

Exit check

A magic value matches at a computed address. Does that prove any caller pointer is valid?

No. Reading an untrusted address may already be invalid; diagnostics need trustworthy ownership and bounds.

9 / 9
←/→ or click edges to navigate · ? help · N notes · F fullscreen