ZetCode

The storage allocator in K&R C

last modified December 5, 2026 K&R C 1978

The linked lists and binary trees articles took their storage from malloc and gave it back with free. These functions are ordinary C. The book writes two allocators: a simple one in the chapter on pointers, which must be freed in the reverse order, and a general one in the chapter on the UNIX system, which gets its memory from the system and keeps the free blocks in a list. This article writes both, under names that do not clash with the library.

A stack of characters

The simplest allocator hands out pieces of one large array, from the start to the end. A pointer marks the first free character. Storage is freed by moving the pointer back, so it must be freed in the reverse order of allocation, like the values of a stack.

stackalloc.c
#include <stdio.h>

#define ALLOCSIZE 100           /* size of the storage */

char allocbuf[ALLOCSIZE];       /* the storage */
char *allocp = allocbuf;        /* the next free position */

char *alloc(n)                  /* a pointer to n free characters */
int n;
{
    if (allocbuf + ALLOCSIZE - allocp >= n) {   /* it fits */
        allocp += n;
        return allocp - n;
    }
    return NULL;                /* not enough room */
}

int afree(p)                    /* free the storage from p on */
char *p;
{
    if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
        allocp = p;
    return 0;
}

int report(name, p)
char *name, *p;
{
    if (p == NULL)
        printf("%s: no room\n", name);
    else
        printf("%s: offset %d\n", name, (int) (p - allocbuf));
    return 0;
}

int main()
{
    char *a, *b, *c;

    a = alloc(40);
    report("a", a);
    b = alloc(50);
    report("b", b);
    c = alloc(20);
    report("c", c);
    afree(b);
    c = alloc(20);
    report("c", c);
    return 0;
}

allocbuf is the storage, and allocp points to its first free character. alloc checks that n characters fit between allocp and the end of the array, advances the pointer, and returns its old value. When the request does not fit, it returns NULL. afree moves the pointer back to p, which frees everything from p on; a pointer outside the array is ignored. 40 and 50 characters fit in the 100 of the array, 20 more do not, but after b is freed they do, at the place where b was.

$ gcc -std=c89 -pedantic -Wall -Wextra -o stackalloc stackalloc.c
$ ./stackalloc
a: offset 0
b: offset 40
c: no room
c: offset 40

Freeing in the wrong order

The allocator cannot check how its storage is used. A program that frees a block too early, or in the wrong order, gets no error message; its data is simply overwritten later.

order.c
#include <stdio.h>
#include <string.h>

#define ALLOCSIZE 100

char allocbuf[ALLOCSIZE];
char *allocp = allocbuf;

char *alloc(n)
int n;
{
    if (allocbuf + ALLOCSIZE - allocp >= n) {
        allocp += n;
        return allocp - n;
    }
    return NULL;
}

int afree(p)
char *p;
{
    if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
        allocp = p;
    return 0;
}

char *strsave(s)        /* a copy of s in storage from alloc */
char *s;
{
    char *p;

    if ((p = alloc(strlen(s) + 1)) != NULL)
        strcpy(p, s);
    return p;
}

int main()
{
    char *first, *second, *third;

    first = strsave("tide");
    second = strsave("harbour");
    printf("%s %s\n", first, second);
    afree(first);               /* frees second as well */
    third = strsave("lighthouse");
    printf("%s %s %s\n", first, second, third);
    return 0;
}

strsave copies a string into storage from alloc. first gets the five characters of "tide" and second the next eight. Freeing first moves the pointer back to the start, which frees second as well, although the program still uses it. The next string is copied over both. first and third point to the same place, and second now points into the middle of lighthouse.

$ gcc -std=c89 -pedantic -Wall -Wextra -o order order.c
$ ./order
tide harbour
lighthouse house lighthouse

Asking the system with sbrk

A general allocator cannot work from a fixed array; it asks the operating system for more memory when it needs it. On UNIX, the data of a program ends at an address called the break. sbrk(n) moves the break up by n bytes and returns the old break, the start of the new space. When the system refuses, it returns -1 cast to a char pointer. sbrk(0) returns the current break.

brk.c
#include <stdio.h>

#define CHUNK 20000
#define NREQ  4

char *sbrk();

int main()
{
    char *start, *end, *p[NREQ];
    int i, n;

    start = sbrk(0);            /* the current end of the data */
    for (n = 0; n < NREQ; n++) {
        p[n] = sbrk(CHUNK);
        if (p[n] == (char *) -1)
            break;
    }
    end = sbrk(0);
    for (i = 0; i < n; i++)
        printf("request %d: %d bytes at offset %u\n", i + 1, CHUNK,
            (unsigned) (p[i] - start));
    if (n < NREQ)
        printf("request %d failed\n", n + 1);
    printf("the data grew by %u bytes\n", (unsigned) (end - start));
    return 0;
}

The program declares sbrk by hand, as the book did; GCC in -std=c89 mode does not declare it in any header. It asks for 20000 bytes four times and prints where each piece starts, relative to the old break. The results are printed only after all requests, because printf gets storage for its buffer from the same place and would move the break between them. The offsets are printed as unsigned, because the PDP-11 cannot hold 40000 in an int.

$ gcc -std=c89 -pedantic -Wall -Wextra -o brk brk.c
$ ./brk
request 1: 20000 bytes at offset 0
request 2: 20000 bytes at offset 20000
request 3: 20000 bytes at offset 40000
request 4: 20000 bytes at offset 60000
the data grew by 80000 bytes

On the PDP-11, the code, the data, and the stack of a program share 64 kilobytes: the data grows up after the code, and the stack grows down from the top. The first two requests fit, and the third would run into the stack, so the system refuses it.

$ cc brk.c
$ a.out
request 1: 20000 bytes at offset 0
request 2: 20000 bytes at offset 20000
request 3 failed
the data grew by 40000 bytes

The block header

The general allocator gives out blocks of different sizes and must know the size of each block when it is freed. Each block therefore starts with a header, which holds the size of the block and a pointer to the next free block. The program sees only the space after the header.

mem.h
typedef long ALIGN;             /* the type with the strictest alignment */

union header {                  /* the header of a block */
    struct {
        union header *h_next;   /* the next block on the free list */
        unsigned h_size;        /* the size of this block in units */
    } s;
    ALIGN x;                    /* never used; aligns the blocks */
};

typedef union header HEADER;

char *blkalloc();
int blkfree();

The header is a union of a structure and a long. The long is never used; it makes the union as large and as strictly aligned as a long. Every block is a whole number of headers, so if the header is suitably aligned, so is the space after it, and any type of data can be stored there. The type name ALIGN collects this machine dependence in one place: the book used an int, which was enough on the PDP-11, and a long is enough for the programs here on both machines. The sizes are counted in units, the size of a header.

units.c
#include <stdio.h>
#include "mem.h"

int main()
{
    static unsigned sizes[] = { 1, 8, 10, 100, 1000 };
    unsigned nbytes, nunits;
    int i;

    printf("a header takes %d bytes\n", (int) sizeof(HEADER));
    for (i = 0; i < 5; i++) {
        nbytes = sizes[i];
        nunits = (nbytes + sizeof(HEADER) - 1) / sizeof(HEADER) + 1;
        printf("request %4u: %3u units = %4u bytes\n",
            nbytes, nunits, nunits * (unsigned) sizeof(HEADER));
    }
    return 0;
}

A request of nbytes needs the bytes rounded up to whole units, plus one unit for the header. The program prints the size of the header and the units for a few requests. On x86-64, a header takes 16 bytes: an 8-byte pointer, a 4-byte unsigned, and padding. Even a request for one byte takes 32 bytes.

$ gcc -std=c89 -pedantic -Wall -Wextra -o units units.c
$ ./units
a header takes 16 bytes
request    1:   2 units =   32 bytes
request    8:   2 units =   32 bytes
request   10:   2 units =   32 bytes
request  100:   8 units =  128 bytes
request 1000:  64 units = 1024 bytes

On the PDP-11, a pointer and an unsigned take two bytes each, so a header has four bytes, and a small request costs much less.

$ cc units.c
$ a.out
a header takes 4 bytes
request    1:   2 units =    8 bytes
request    8:   3 units =   12 bytes
request   10:   4 units =   16 bytes
request  100:  26 units =  104 bytes
request 1000: 251 units = 1004 bytes

Allocating from the free list

The free blocks form a list that is sorted by address and closed into a ring: the last block points back to the first. To allocate, the allocator walks the ring until it finds a block that is large enough. When it gets around the ring without finding one, it asks the system for more.

memget.c
#include <stdio.h>
#include "mem.h"

#define NALLOC 128              /* the least units to ask the system for */

static HEADER base;             /* an empty list to start with */
HEADER *freep = NULL;           /* where the last search ended */

/* ask the system for at least nu units */
static HEADER *morecore(nu)
unsigned nu;
{
    char *cp, *sbrk();
    HEADER *up;

    if (nu < NALLOC)
        nu = NALLOC;
    cp = sbrk(nu * sizeof(HEADER));
    if (cp == (char *) -1)      /* no more memory */
        return NULL;
    up = (HEADER *) cp;
    up->s.h_size = nu;
    blkfree((char *) (up + 1)); /* put the new block on the free list */
    return freep;
}

/* storage for nbytes bytes, or NULL */
char *blkalloc(nbytes)
unsigned nbytes;
{
    HEADER *p, *prevp;
    unsigned nunits;

    nunits = (nbytes + sizeof(HEADER) - 1) / sizeof(HEADER) + 1;
    if ((prevp = freep) == NULL) {      /* the first call */
        base.s.h_next = freep = prevp = &base;
        base.s.h_size = 0;
    }
    for (p = prevp->s.h_next; ; prevp = p, p = p->s.h_next) {
        if (p->s.h_size >= nunits) {    /* big enough */
            if (p->s.h_size == nunits)  /* exactly: unlink it */
                prevp->s.h_next = p->s.h_next;
            else {                      /* give out the tail end */
                p->s.h_size -= nunits;
                p += p->s.h_size;
                p->s.h_size = nunits;
            }
            freep = prevp;
            return (char *) (p + 1);
        }
        if (p == freep)                 /* around the list: none fits */
            if ((p = morecore(nunits)) == NULL)
                return NULL;
    }
}

On the first call, the ring is made of base alone, a degenerate block of size zero. freep remembers where the last search ended, and the next search starts there, which spreads the allocations over the ring. A block of exactly the right size is unlinked from the ring. A larger block is split: its size is reduced, and the end of it becomes the new block, so the ring needs no change. The function returns the address after the header. morecore asks the system for at least NALLOC units, because each call of sbrk is expensive, writes a header into the new space, and hands the space to blkfree, which adds it to the ring. It is static, so it is private to the file. The pointer freep is external, because the free function in the next section needs it too.

Returning blocks

A freed block goes back into the ring at its place by address. If it borders on a free block, the two are joined into one, so that the free memory does not crumble into pieces too small to use.

memfree.c
#include <stdio.h>
#include "mem.h"

extern HEADER *freep;

/* put the block at ap on the free list, joined with free neighbours */
int blkfree(ap)
char *ap;
{
    HEADER *bp, *p;

    bp = (HEADER *) ap - 1;     /* the header of the block */
    for (p = freep; !(bp > p && bp < p->s.h_next); p = p->s.h_next)
        if (p >= p->s.h_next && (bp > p || bp < p->s.h_next))
            break;              /* at the start or the end of the list */

    if (bp + bp->s.h_size == p->s.h_next) {    /* join the next block */
        bp->s.h_size += p->s.h_next->s.h_size;
        bp->s.h_next = p->s.h_next->s.h_next;
    } else
        bp->s.h_next = p->s.h_next;
    if (p + p->s.h_size == bp) {               /* join the previous one */
        p->s.h_size += bp->s.h_size;
        p->s.h_next = bp->s.h_next;
    } else
        p->s.h_next = bp;
    freep = p;
    return 0;
}

blkfree finds the header just before the space it receives. The loop looks for the free block p after which the freed block lies. The ring is sorted by address, except at the one place where the last block points back to the first; a block below the first or above the last goes there. If the freed block ends where the next free block starts, the two are joined; if the previous free block ends where the freed one starts, they are joined too.

words.c
#include <stdio.h>
#include <string.h>
#include "mem.h"

int main()
{
    static char *words[] = { "tide", "harbour", "gulls", "quay" };
    char *copy[4];
    int i;

    for (i = 0; i < 4; i++) {
        copy[i] = blkalloc((unsigned) strlen(words[i]) + 1);
        if (copy[i] == NULL) {
            printf("out of memory\n");
            return 1;
        }
        strcpy(copy[i], words[i]);
    }
    for (i = 0; i < 4; i++) {
        printf("%s ", copy[i]);
        blkfree(copy[i]);
    }
    printf("\n");
    return 0;
}

A short test copies four words into blocks from blkalloc, prints them, and frees the blocks.

$ gcc -std=c89 -pedantic -Wall -Wextra -o words words.c memget.c memfree.c
$ ./words
tide harbour gulls quay 

Watching the free list

The joining of blocks is easier to see in the free list itself. The next program prints the sizes of the free blocks, in units, after each step.

freelist.c
#include <stdio.h>
#include "mem.h"

extern HEADER *freep;

/* print the sizes of the free blocks in address order */
int showfree(title)
char *title;
{
    HEADER *p;

    printf("%-10s", title);
    for (p = freep; p->s.h_size != 0; p = p->s.h_next)
        ;                       /* find the base, size 0 */
    for (p = p->s.h_next; p->s.h_size != 0; p = p->s.h_next)
        printf(" %u", p->s.h_size);
    printf("\n");
    return 0;
}

int main()
{
    char *a, *b, *c;

    a = blkalloc(100);
    b = blkalloc(200);
    c = blkalloc(100);
    showfree("a, b, c:");
    blkfree(b);
    showfree("free b:");
    blkfree(a);
    showfree("free a:");
    blkfree(c);
    showfree("free c:");
    return 0;
}

showfree walks the ring to base, the only block of size zero, and then prints the blocks that follow, in address order. The program allocates 100, 200, and 100 bytes and frees the blocks in another order. The first request makes morecore get 128 units, and the three blocks are cut from its end: a at the top, b below it, and c below b.

$ gcc -std=c89 -pedantic -Wall -Wextra -o freelist freelist.c memget.c memfree.c
$ ./freelist
a, b, c:   98
free b:    98 14
free a:    98 22
free c:    128

The three blocks take 8, 14, and 8 units, and 98 units stay free. The freed b has c below it and a above it, so it stays a separate block. a borders on b and joins it. c fills the gap between the two free blocks, and all of the memory is one block of 128 units again.

The allocator compiles unchanged on the PDP-11. The units are four bytes there, so the same requests take 26, 51, and 26 units, but the blocks are joined in the same way.

$ cc freelist.c memget.c memfree.c
freelist.c:
memget.c:
memfree.c:
$ a.out
a, b, c:   25
free b:    25 51
free a:    25 77
free c:    128

Source

Dennis Ritchie: C Reference Manual (1975)

Linux manual: brk, sbrk

In this article we have written storage allocators in K&R C: the stack allocator alloc and afree, what happens when it is freed in the wrong order, the break and sbrk, block headers and alignment, and a free-list allocator that splits and joins blocks, on GCC and on the PDP-11. The standard library article lists the library's own allocation functions. The next article covers porting K&R C to modern C.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.