C allocator alignment: payload and next block

What C allocator alignment actually requires

C allocator alignment requires the header, payload and next block to respect the chosen alignment. Round the header footprint up for the payload offset, then round the payload end for the block span: with a 24-byte header, 13-byte request and 16-byte alignment, those values are 32 and 48 bytes.

For a teaching allocator, choose an explicit alignment contract. Call it A: every returned payload and every block start will be aligned to A. Assume that A also satisfies the header type’s alignment. In C11, _Alignof(T) reports a type’s requirement; _Alignof(max_align_t) is a useful starting point for a contract covering fundamental alignments. Its value depends on the implementation—16 is an example, not a C guarantee.

This article assumes one contiguous arena whose base already meets that contract, fixed-size inline headers, and offsets measured in C bytes. It covers ordinary, fundamentally aligned objects, not types with extended alignment requirements. See C objects, effective types and alignment for the language rules behind those constraints.

A 24-byte header and a 13-byte request

Suppose A = 16, the header occupies 24 bytes, and the caller requests 13 bytes. All offsets below are relative to the aligned arena base. A range such as [0, 24) includes offset 0 but excludes offset 24.

Simply returning the address immediately after the header puts the payload at offset 24. That is not a multiple of 16. Round the header footprint up to 32, leaving 8 bytes between header and payload.

The payload now occupies [32, 45). If the next header starts immediately after it, that header starts at offset 45. The first payload is aligned, but the next block is not. With the same 32-byte payload offset inside that block, its payload would start at 77—also not a multiple of 16. Depending on the header type, even accessing that next header could already violate its alignment requirement.

Round the occupied span, 45 bytes, up to 48. The extra 3 bytes belong to the allocator’s padding, not to the caller’s requested payload. The next block then starts at offset 48, and its payload starts at 48 + 32 = 80. Both are multiples of 16.

The diagram compares the broken stride with the corrected layout; the offset labels, not just the colours, identify each boundary.

Two layouts with 16-byte alignment. A 24-byte header and 8 bytes of padding put the 13-byte payload at offset 32. Without tail padding the next block begins at 45, misaligned; 3 bytes of tail padding move it to aligned offset 48. Ranges exclude their end.

The corrected first block contains:

  • Header: [0, 24), 24 bytes.
  • Padding before payload: [24, 32), 8 bytes.
  • Requested payload: [32, 45), 13 bytes.
  • Padding after payload: [45, 48), 3 bytes.

Want to see the arithmetic run? Run the checked C11 example in the browser: it executes the exact downloadable source against 18 fixed checks, with no account or compiler setup. Those tests use fixed cases, not the calculator’s adjustable inputs; changing the three inputs updates the browser layout only. The run checks layout arithmetic, not an allocator or a completed course.

Align the payload offset and the block span separately

Let H be the header’s actual size, including any padding the compiler puts inside its representation, and n the requested payload size. For this fixed-header design:

  1. Round H up to a multiple of A. That is the payload offset within a block.
  2. Add n to that offset, then round the result up to a multiple of A. That is the block span.
  3. Add the block span to the current block’s start offset to find the next boundary.

Because the current block start is aligned, an aligned payload offset gives an aligned payload address. Because the block span is a multiple of A, adding it gives another aligned block start. The same reasoning applies to every subsequent block.

C struct padding alone does not establish this invariant. sizeof(Header) is compatible with the header’s own alignment, which may be weaker than the alignment promised for payloads. Use the actual sizeof(Header) and check the header’s alignment rather than assuming a particular field layout.

Perform size calculations before forming pointers. To round an integer byte count x for positive A, calculate the remainder r = x % A. Add zero if r is zero; otherwise add A - r. Before any addition, require the left operand to be no greater than SIZE_MAX minus the right operand. This prevents unsigned wraparound from making a huge request appear small.

Apply that check to rounding the header footprint, adding the request size and rounding the resulting span. Finally, after checking that the current start offset is no greater than the arena size, require the block span to fit in the remaining capacity. Only then compute the next offset and derive addresses within the arena. An aligned next offset equal to the arena size is an end marker, not storage for another header.

The familiar bit-mask rounding expression can be appropriate for integer sizes when the alignment is a power of two and overflow is checked. It is not a reason to cast pointers to integers, round their bits, and cast back. Pointer–integer conversions have implementation-dependent aspects; integer address arithmetic is not a portable substitute for bounded byte-pointer arithmetic within valid storage.

Alignment is necessary, not sufficient, for valid C

A declared unsigned char arena[N] is useful for modelling bytes. Merely aligning it and casting a portion to Header * does not turn it into general-purpose storage for arbitrary typed objects: declared objects have effective types, and aliasing rules still apply.

For a byte-array teaching model, keep metadata as byte representations and use memcpy to and from real header objects, or keep metadata outside the arena. If you want clients to store arbitrary objects directly, use appropriate allocated storage and reason about its effective type, bounds and lifetime. Alignment checks alone do not prove those accesses valid.

Byte traversal uses an unsigned char * into the arena, not arithmetic on void *—the latter is an extension on some compilers. Do not form an out-of-bounds pointer and then check whether it was valid. Check integer offsets and available capacity first.

Test the invariant across allocations and splits

A one-allocation test misses the stride bug. With A = 16 and H = 24, the payload offset is always 32 in this design:

  • Requests of 1, 13 or 16 bytes each require a 48-byte block span.
  • A request of 17 bytes requires a 64-byte block span.

Allocate several blocks in succession and verify their start offsets and payload offsets are multiples of A. Check a request that exactly fits the remaining arena and one that exceeds it. Exercise overflow rejection with large sizes; define a separate policy for zero-size requests.

When splitting a free block, place the remainder at the rounded block boundary. Split only if the remainder can hold your design’s minimum valid free block, including its metadata. When coalescing physically adjacent blocks, spans that are multiples of A sum to another multiple of A; still validate adjacency, sizes and bounds. Otherwise a later split can reintroduce a layout bug.

A teaching allocator is not production malloc

This is one deliberately simple layout, not a description of every malloc implementation. Production allocators may use size classes, separate metadata, multiple arenas and platform-specific memory sources. They also need policies for concurrency, fragmentation, invalid inputs and other cases omitted here.

Our teaching contract deliberately aligns even tiny payloads to the same A. Do not assume every production malloc provides the same fixed alignment for all small requests, or supports arbitrary over-aligned types. The GNU C Library’s portability notes explain differences between implementations; WG14’s alignment discussion records the small-allocation issue. Use an appropriate aligned-allocation interface when your types require it.

Try the alignment checks

The live alignment lesson is a related exercise, not an implementation of the inline-header layout above. It asks you to implement align_offset and arena_take for aligned reservations in a 64-byte byte arena. The sample uses an 8-byte alignment policy, has no headers, and is educational—not production malloc.

Download the unfinished C starter and seven-check test harness. Extract the ZIP, open a terminal in the extracted heapcraft-arena-alignment folder (the one containing learner.c and tests.c), and compile with a C11 compiler such as GCC or Clang:

cc -std=c11 -Wall -Wextra \
  -pedantic learner.c tests.c \
  -o alignment-tests
./alignment-tests

You can use gcc or clang instead of cc. On Windows, run the commands in WSL or a GCC/Clang terminal; for a native Windows terminal, use -o alignment-tests.exe and run ./alignment-tests.exe.

The starter is meant to compile but initially fails four checks: rounding offsets, reserving consecutive aligned slices, accepting an exact fit, and preserving earlier payload bytes. The three rejection checks already pass because the unfinished reservation function returns SIZE_MAX for every request. Implement the two functions in learner.c; leave tests.c unchanged. A completed run prints seven PASS lines and exits successfully. Compiler errors mean it did not build—don’t treat an old executable as a passing run.

Local edits and test results do not sync automatically. When you’re ready, paste your learner.c into the lesson editor and run the checks there; sign in or create an account and verify there to save completion and continue in the free sequential preview.