medium.com 4 min read Original Source

Building a Memory Allocator from Scratch: Why TLSF is the Real Deal

I recently dove into building a custom memory allocator for an embedded project. Standard malloc()? Too unpredictable for real-time constraints. So naturally, I did what any developer would do: rolled my own.

Spoiler alert: I learned why the professionals use TLSF (Two-Level Segregated Fit), and why my “clever” solution wasn’t as clever as I thought.

The Journey: Three Levels of Sophistication

Level 1: The Naive Approach — One Giant List

My first attempt was embarrassingly simple:

#define HEAP_SIZE (64*1024)
static uint8_t heap[HEAP_SIZE];

typedef struct block_t {
    uint32_t size;
    struct block_t *next;
    uint8_t free;
} block_t;

static block_t *free_list;  // ONE list for everything
#define HEAP_SIZE (64*1024)
static uint8_t heap[HEAP_SIZE];

typedef struct block_t {
    uint32_t size;
    struct block_t *next;
    uint8_t free;
} block_t;

static block_t *free_list;  // ONE list for everything

The allocation strategy:

PSEUDOCODE:
1. Initialize: Mark entire heap as one giant free block
2. Allocate: Walk the ENTIRE list, find first fit, split if oversized
3. Free: Mark block free, merge adjacent free blocks
PSEUDOCODE:
1. Initialize: Mark entire heap as one giant free block
2. Allocate: Walk the ENTIRE list, find first fit, split if oversized
3. Free: Mark block free, merge adjacent free blocks

The Implementation:

free && curr->size >= size) {
// Split if we have leftover space
if (curr->size >= size + sizeof(block_t) + 8) {
block_t *newb = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
newb->size = curr->size – size – sizeof(block_t);
newb->free = 1;
newb->next = curr->next;
curr->size = size;
curr->next = newb;
}
curr->free = 0;
return (void *)((uint8_t*)curr + sizeof(block_t));
}
curr = curr->next;
}
return NULL; // Out of memory
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

void *mm_alloc(uint32_t size) {
    block_t *curr = free_list;

    // Search EVERYTHING
    while (curr) {
        if (curr->free && curr->size >= size) {
            // Split if we have leftover space
            if (curr->size >= size + sizeof(block_t) + 8) {
                block_t *newb = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
                newb->size = curr->size - size - sizeof(block_t);
                newb->free = 1;
                newb->next = curr->next;
                curr->size = size;
                curr->next = newb;
            }
            curr->free = 0;
            return (void *)((uint8_t*)curr + sizeof(block_t));
        }
        curr = curr->next;
    }
    return NULL;  // Out of memory
}
void *mm_alloc(uint32_t size) {
    block_t *curr = free_list;

    // Search EVERYTHING
    while (curr) {
        if (curr->free && curr->size >= size) {
            // Split if we have leftover space
            if (curr->size >= size + sizeof(block_t) + 8) {
                block_t *newb = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
                newb->size = curr->size - size - sizeof(block_t);
                newb->free = 1;
                newb->next = curr->next;
                curr->size = size;
                curr->next = newb;
            }
            curr->free = 0;
            return (void *)((uint8_t*)curr + sizeof(block_t));
        }
        curr = curr->next;
    }
    return NULL;  // Out of memory
}

The problem?

In a fragmented 64KB heap with hundreds of allocations, I could be searching through 1000+ blocks for every single allocation. That’s O(n) behavior where n is the total number of blocks in the entire heap.

For a real-time system running at 1kHz? Absolutely unacceptable.

Level 2: Segregated Free Lists

I thought I’d solved it. Instead of one massive list, why not use separate lists for different size classes?

#define NUM_POOLS 4

static block_t *free_lists[NUM_POOLS];  // Separate list per size
static const uint32_t pool_sizes[] = {16, 64, 256, 1024};
#define NUM_POOLS 4

static block_t *free_lists[NUM_POOLS];  // Separate list per size
static const uint32_t pool_sizes[] = {16, 64, 256, 1024};

The idea: Carve up the heap into size-specific pools.

<button data-code="void mm_init() {
uint8_t *ptr = heap;
size_t remaining = HEAP_SIZE;

// Allocate 25% of heap to each pool
for (int i = 0; i 0; i++) {
size_t pool_bytes = HEAP_SIZE / NUM_POOLS;
free_lists[i] = (block_t *)ptr;
free_lists[i]->size = pool_bytes – sizeof(block_t);
free_lists[i]->next = NULL;
free_lists[i]->free = 1;
free_lists[i]->pool_id = i;

ptr += pool_bytes;
remaining -= pool_bytes;
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

void mm_init() {
    uint8_t *ptr = heap;
    size_t remaining = HEAP_SIZE;

    // Allocate 25% of heap to each pool
    for (int i = 0; i < NUM_POOLS && remaining > 0; i++) {
        size_t pool_bytes = HEAP_SIZE / NUM_POOLS;
        free_lists[i] = (block_t *)ptr;
        free_lists[i]->size = pool_bytes - sizeof(block_t);
        free_lists[i]->next = NULL;
        free_lists[i]->free = 1;
        free_lists[i]->pool_id = i;

        ptr += pool_bytes;
        remaining -= pool_bytes;
    }
}
void mm_init() {
    uint8_t *ptr = heap;
    size_t remaining = HEAP_SIZE;

    // Allocate 25% of heap to each pool
    for (int i = 0; i < NUM_POOLS && remaining > 0; i++) {
        size_t pool_bytes = HEAP_SIZE / NUM_POOLS;
        free_lists[i] = (block_t *)ptr;
        free_lists[i]->size = pool_bytes - sizeof(block_t);
        free_lists[i]->next = NULL;
        free_lists[i]->free = 1;
        free_lists[i]->pool_id = i;

        ptr += pool_bytes;
        remaining -= pool_bytes;
    }
}

Now allocation searches only the relevant pool:

<button data-code="void *mm_alloc(uint32_t size) {
// Find best-fit pool
int pool = -1;
for (int i = 0; i = size) {
pool = i;
break;
}
}

if (pool == -1) pool = NUM_POOLS – 1;

// Search ONLY this pool's list
block_t *curr = free_lists[pool];
while (curr) {
if (curr->free && curr->size >= size) {
// Smarter splitting logic
if (curr->size >= size + sizeof(block_t) + pool_sizes[pool]/4) {
block_t *new_block = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
new_block->size = curr->size – size – sizeof(block_t);
new_block->free = 1;
new_block->next = curr->next;
new_block->pool_id = pool;

curr->size = size;
curr->next = new_block;
}
curr->free = 0;
return (void *)((uint8_t*)curr + sizeof(block_t));
}
curr = curr->next;
}

return NULL;
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

void *mm_alloc(uint32_t size) {
    // Find best-fit pool
    int pool = -1;
    for (int i = 0; i < NUM_POOLS; i++) {
        if (pool_sizes[i] >= size) {
            pool = i;
            break;
        }
    }

    if (pool == -1) pool = NUM_POOLS - 1;

    // Search ONLY this pool's list
    block_t *curr = free_lists[pool];
    while (curr) {
        if (curr->free && curr->size >= size) {
            // Smarter splitting logic
            if (curr->size >= size + sizeof(block_t) + pool_sizes[pool]/4) {
                block_t *new_block = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
                new_block->size = curr->size - size - sizeof(block_t);
                new_block->free = 1;
                new_block->next = curr->next;
                new_block->pool_id = pool;

                curr->size = size;
                curr->next = new_block;
            }
            curr->free = 0;
            return (void *)((uint8_t*)curr + sizeof(block_t));
        }
        curr = curr->next;
    }

    return NULL;
}
void *mm_alloc(uint32_t size) {
    // Find best-fit pool
    int pool = -1;
    for (int i = 0; i < NUM_POOLS; i++) {
        if (pool_sizes[i] >= size) {
            pool = i;
            break;
        }
    }

    if (pool == -1) pool = NUM_POOLS - 1;

    // Search ONLY this pool's list
    block_t *curr = free_lists[pool];
    while (curr) {
        if (curr->free && curr->size >= size) {
            // Smarter splitting logic
            if (curr->size >= size + sizeof(block_t) + pool_sizes[pool]/4) {
                block_t *new_block = (block_t *)((uint8_t*)curr + sizeof(block_t) + size);
                new_block->size = curr->size - size - sizeof(block_t);
                new_block->free = 1;
                new_block->next = curr->next;
                new_block->pool_id = pool;

                curr->size = size;
                curr->next = new_block;
            }
            curr->free = 0;
            return (void *)((uint8_t*)curr + sizeof(block_t));
        }
        curr = curr->next;
    }

    return NULL;
}

Updated pseudocode:

ALLOCATION:
1. Determine best pool for requested size (O(1))
2. Search that pool's free list (O(m) where m = blocks in pool)
3. Split block only if remainder is useful
4. Mark allocated, return pointer

DEALLOCATION:
1. Mark block as free
2. Coalesce with adjacent blocks in same pool
3. Prevents cross-contamination between pools
ALLOCATION:
1. Determine best pool for requested size (O(1))
2. Search that pool's free list (O(m) where m = blocks in pool)
3. Split block only if remainder is useful
4. Mark allocated, return pointer

DEALLOCATION:
1. Mark block as free
2. Coalesce with adjacent blocks in same pool
3. Prevents cross-contamination between pools

The improvement:

Instead of searching 1000 blocks, I’m now searching maybe 250 blocks in the relevant pool. That’s 4x better!

I felt pretty good about myself. About 120 lines of code, significantly better performance, and I learned a ton about memory management.

Then I learned about TLSF.


Level 3: TLSF – How the Pros Do It

TLSF stands for Two-Level Segregated Fit, and it’s the industry standard for deterministic memory allocation in embedded systems.

Here’s the thing I missed: I was still doing linked-list traversal. I just made the lists shorter.

TLSF? It eliminates traversal entirely.

The TLSF Magic: Bitmaps

Instead of searching through lists, TLSF uses a two-level bitmap structure:

FIRST LEVEL: Size classes (powers of 2)
  16, 32, 64, 128, 256, 512, 1024...

SECOND LEVEL: Subdivisions within each class
  Example: 128-256 range gets split into bins
  128-144, 144-160, 160-176, 176-192, etc.
FIRST LEVEL: Size classes (powers of 2)
  16, 32, 64, 128, 256, 512, 1024...

SECOND LEVEL: Subdivisions within each class
  Example: 128-256 range gets split into bins
  128-144, 144-160, 160-176, 176-192, etc.

My approach visualized:

Pool for 64-byte blocks:
  [Free] → [Allocated] → [Free] → [Free] → [Allocated] → NULL

To find free block: walk the list ↑ (slow, unpredictable)
Pool for 64-byte blocks:
  [Free] → [Allocated] → [Free] → [Free] → [Allocated] → NULL

To find free block: walk the list ↑ (slow, unpredictable)

TLSF approach:

First Level Bitmap (size classes):
  [1][1][0][1][1][1]  ← 1 = has free blocks available
   ↓  ↓     ↓  ↓  ↓
  16 32    64 128 256

Second Level Bitmap for 128-byte class:
  [0][1][1][0]  ← subdivisions within 128-256 range
      ↓  ↓
    144 160

Direct array access: blocks[3][1] = pointer to 144-byte free block
First Level Bitmap (size classes):
  [1][1][0][1][1][1]  ← 1 = has free blocks available
   ↓  ↓     ↓  ↓  ↓
  16 32    64 128 256

Second Level Bitmap for 128-byte class:
  [0][1][1][0]  ← subdivisions within 128-256 range
      ↓  ↓
    144 160

Direct array access: blocks[3][1] = pointer to 144-byte free block

The Performance Difference

My allocator finding a 150-byte block:

1. Calculate pool index → O(1)
2. Go to 256-byte pool list
3. Walk: block1 (allocated) → skip
4. Walk: block2 (too small) → skip
5. Walk: block3 (allocated) → skip
6. Walk: block4 (free, fits!) → return

⏱️ Time: O(m) - depends on list length and fragmentation
1. Calculate pool index → O(1)
2. Go to 256-byte pool list
3. Walk: block1 (allocated) → skip
4. Walk: block2 (too small) → skip
5. Walk: block3 (allocated) → skip
6. Walk: block4 (free, fits!) → return

⏱️ Time: O(m) - depends on list length and fragmentation

TLSF finding a 150-byte block:

<button data-code="void *tlsf_alloc(uint32_t size) {
// 1. Map size to indices using bit operations
int fl = __builtin_clz(size); // O(1) – CPU instruction!
int sl = calculate_second_level(size); // O(1) – bit math

// 2. Check bitmap – is there a free block?
if (bitmap[fl] & (1 <

void *tlsf_alloc(uint32_t size) {
    // 1. Map size to indices using bit operations
    int fl = __builtin_clz(size);        // O(1) - CPU instruction!
    int sl = calculate_second_level(size);  // O(1) - bit math

    // 2. Check bitmap - is there a free block?
    if (bitmap[fl] & (1 << sl)) {          // O(1) - single bit check
        block_t *block = matrix[fl][sl];    // O(1) - direct array lookup
        return allocate(block);
    }

    // 3. Find next available size using bit scan
    int next = __builtin_ffs(bitmap[fl]);   // O(1) - another CPU instruction
    return allocate(matrix[fl][next]);
}
void *tlsf_alloc(uint32_t size) {
    // 1. Map size to indices using bit operations
    int fl = __builtin_clz(size);        // O(1) - CPU instruction!
    int sl = calculate_second_level(size);  // O(1) - bit math

    // 2. Check bitmap - is there a free block?
    if (bitmap[fl] & (1 << sl)) {          // O(1) - single bit check
        block_t *block = matrix[fl][sl];    // O(1) - direct array lookup
        return allocate(block);
    }

    // 3. Find next available size using bit scan
    int next = __builtin_ffs(bitmap[fl]);   // O(1) - another CPU instruction
    return allocate(matrix[fl][next]);
}

Steps:

<button data-code="1. Calculate indices: fl=7, sl=2 → O(1)
2. Check bitmap: bitmap[7] & (1<

1. Calculate indices: fl=7, sl=2 → O(1)
2. Check bitmap: bitmap[7] & (1<<2) → O(1)
3. Grab block: blocks[7][2] → O(1)

⏱️ Time: O(1) - ALWAYS three operations, regardless of heap state
1. Calculate indices: fl=7, sl=2 → O(1)
2. Check bitmap: bitmap[7] & (1<<2) → O(1)
3. Grab block: blocks[7][2] → O(1)

⏱️ Time: O(1) - ALWAYS three operations, regardless of heap state

The key insight: TLSF uses hardware bit-scanning instructions. Modern CPUs can find the first set bit in a bitmap in a single clock cycle.

Comparison:

The Honest Truth: When to Use Each

Use Basic Free-List When:

  • Learning about memory allocation
  • Prototyping
  • Non-critical hobby projects
  • You have infinite time budgets

Use Segregated Lists When:

  • Soft real-time requirements (some jitter acceptable)
  • You want better performance than malloc
  • Code simplicity matters
  • You’re willing to accept bounded unpredictability

Use TLSF When:

  • Hard real-time requirements
  • Safety-critical systems
  • Aerospace, medical, automotive
  • Zero jitter tolerance
  • Professional embedded systems

What I Learned

Building my own allocator was absolutely worth it for understanding how memory management works. I learned about:

  • Fragmentation patterns
  • Block splitting strategies
  • Coalescing algorithms
  • The tradeoff between complexity and performance

TLSF represents a paradigm shift, eliminating the search entirely by using bitmaps and direct indexing. That’s the difference between incremental improvement and true innovation.

Final Thoughts

There’s immense value in building things from scratch, even when better solutions exist. I now understand why TLSF is designed the way it is. I understand the tradeoffs at a visceral level.

Build your own allocator to learn. Use TLSF to ship.