Alignment and Splitting
Make blocks usable and tidy.
Why Alignment Matters
Every type has an alignment requirement: its address must be a multiple of some power of two. A double typically needs 8-byte alignment.
Because malloc does not know what you will store, it must return pointers aligned for the strictest type, usually 16 bytes on 64-bit systems.
#include <stdalign.h>
/* the strictest fundamental alignment */
size_t strict = alignof(max_align_t); /* often 16 */The align_up Trick
Rounding a size up to the next multiple of a power-of-two alignment is a classic bit trick: add a - 1, then mask off the low bits.
This works only when a is a power of two, which all real alignments are.
static size_t align_up(size_t n, size_t a) {
return (n + a - 1) & ~(a - 1);
}
/* align_up(13, 8) == 16, align_up(16, 8) == 16 */All lessons in this course
- How malloc Works
- A Simple Bump Allocator
- Free Lists and Reuse
- Alignment and Splitting