User-defined memory management

suggest change

Specialized allocators can reduce overhead when a program creates many objects with predictable sizes or lifetimes. Common designs include arenas, pools, slab allocators, and free lists.

A fixed-size pool can store the free-list link inside each unused block:

#include <stddef.h>

enum { block_count = 100, payload_size = 32 };

union block {
    union block *next;
    max_align_t alignment;
    unsigned char payload[payload_size];
};

static union block pool[block_count];
static union block *free_list;

void pool_init(void)
{
    for (size_t index = 0; index + 1 < block_count; ++index) {
        pool[index].next = &pool[index + 1];
    }
    pool[block_count - 1].next = NULL;
    free_list = &pool[0];
}

void *pool_alloc(void)
{
    if (free_list == NULL) {
        return NULL;
    }

    union block *result = free_list;
    free_list = result->next;
    return result->payload;
}

void pool_free(void *pointer)
{
    if (pointer == NULL) {
        return;
    }

    union block *block =
        (union block *)((unsigned char *)pointer -
                        offsetof(union block, payload));
    block->next = free_list;
    free_list = block;
}

This example is intentionally minimal. It is not thread-safe and does not detect foreign pointers, double frees, or use-after-free. Production pools often add validation and synchronization.

Alignment must be derived from the types the allocator promises to support; assuming that eight-byte alignment is universally sufficient is incorrect. max_align_t covers fundamental alignments, while over-aligned types may need a stronger, implementation-specific strategy.

General-purpose allocators must also handle size overflow, splitting and coalescing, fragmentation, metadata corruption, and allocation semantics required by the caller. Prefer the standard allocator unless measurement shows that a specialized ownership model materially helps.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents