Skip to content
systemcoding.dev
Systems Programming

The Complete Guide to Dynamic Memory Allocation in C

Learn malloc, calloc, realloc and free from scratch, the bugs they cause, who owns each pointer, and what glibc does underneath, with tested patterns.

29 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, GNU and FreeBSD logos.

Every C program that handles input of unknown size eventually asks the C library for memory at run time, and every serious C bug story involves what happened to that memory afterward. This guide covers the whole subject from the first malloc() call to the internals of the glibc allocator: how to request memory, resize it, give it back, spot the six classic mistakes, assign ownership so mistakes stop happening, and choose a different strategy when general-purpose allocation is the wrong tool. If you read it top to bottom you will be able to write a growable array, a string builder and a small object pool without leaking or corrupting anything, and you will know what the allocator is doing while your code runs.

The short version fits in one paragraph. malloc(n) returns a pointer to n bytes of uninitialized memory or NULL on failure. calloc(count, size) does the same with zeroed memory and an overflow check. realloc(p, n) resizes a block and may move it. free(p) returns a block to the allocator, and the pointer must not be used afterward. Every block you allocate must be freed exactly once, by the code that owns it, and the rest of this guide is the detail behind that sentence.

The examples assume C17 (and note where C23 differs), GCC 14 and glibc 2.40 on Linux 6.12 with a 64-bit x86 or arm64 CPU. glibc's allocator is the one described in the later sections, and the behavior of the standard functions follows ISO C and POSIX.1-2024. A later set of posts in this series goes deeper into each topic; this page is the map.

Where memory comes from

A running C program has three places to keep data, and dynamic allocation is the third.

StorageLifetimeSize knownTypical use
Static (globals, static locals, string literals)Whole programAt compile timeTables, constants, global state
Automatic (the stack: locals, parameters)The enclosing block or function callAt compile time (or via a variable length array)Temporary values, small buffers
Dynamic (the heap)From malloc() until free()At run timeData whose size or lifetime is only known while running

The stack is fast and tidy. A function's locals appear when it is called and vanish when it returns, so nothing ever needs freeing, and a function cannot hand a pointer to its own local back to its caller, because the storage is gone by then. That second restriction is the reason the heap exists. When a function must create something that outlives it, such as a parsed file, a list of records read from a socket or a buffer that grows as input arrives, the data has to live somewhere that is not tied to a function's lifetime. The heap is that place, and the price is that you, not the compiler, decide when the memory ends.

The stack is also small, usually 8 MiB for the main thread on Linux (ulimit -s shows it), and a function that declares a 100 MiB local array crashes at once. Large or unpredictable amounts of data belong on the heap for that reason alone.

malloc: ask for memory

void *malloc(size_t size) is declared in <stdlib.h>. It returns a pointer suitably aligned for any type, to a block of at least size bytes, or NULL if the request cannot be satisfied. Three rules cover most of its use.

**Check for NULL.** On Linux with default settings, small allocations rarely fail, because the kernel overcommits memory and the real failure shows up later as the out-of-memory killer. That does not make the check optional. A request for an absurd size, a process limit set with ulimit -v or a container's address-space limit all produce a clean NULL, and a program that dereferences it crashes with no explanation.

The contents are indeterminate. The block holds whatever bytes were there before. Reading them before writing is undefined behavior, and the bytes may happen to be zero often enough that the bug survives testing.

Size the request from the type, not by hand. Write sizeof *p, not sizeof(struct Order) and not 4 * 10. The pointer's own type is the single source of truth, and if the type changes, the allocation follows.

first_malloc.cc
#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    double total;
};

int main(void)
{
    struct order *o = malloc(sizeof *o);

    if (o == NULL) {
        fprintf(stderr, "out of memory\n");
        return EXIT_FAILURE;
    }
    o->id = 1042;
    o->total = 59.90;

    printf("order %d totals %.2f\n", o->id, o->total);
    free(o);
    return EXIT_SUCCESS;
}
Text
order 1042 totals 59.90

Compile with gcc -std=c17 -O2 -Wall -Wextra -o first_malloc first_malloc.c. The malloc() call needs no cast: in C, void * converts to any object pointer type implicitly, and a cast only hides a missing #include <stdlib.h> from an old compiler. (C++ is different and requires the cast, which is one reason C and C++ allocation idioms diverge.) The struct is 16 bytes on a typical 64-bit system, because the int is padded to align the double; sizeof *o accounts for that and a hand-written constant would not.

Allocating arrays

For an array of n elements, multiply by the element size: malloc(n * sizeof *arr). The multiplication can overflow size_t. If n comes from a file or a network packet and an attacker picks it so that the product wraps around to a small number, malloc() succeeds with a tiny block and the following loop writes far past it. That is a classic source of heap overflows. The remedy is to use calloc(), which checks the multiplication, or to check it yourself before calling malloc().

array_alloc.cc
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int *make_ints(size_t n)
{
    if (n > SIZE_MAX / sizeof(int)) {
        return NULL;                       /* the product would overflow */
    }
    return malloc(n * sizeof(int));
}

int main(void)
{
    int *a = make_ints(5);
    int *huge = make_ints(SIZE_MAX / 2);

    printf("small: %s\n", a != NULL ? "ok" : "failed");
    printf("huge:  %s\n", huge != NULL ? "ok" : "failed");
    free(a);
    free(huge);
    return EXIT_SUCCESS;
}
Text
small: ok
huge:  failed

The huge call returns NULL from the overflow check without ever reaching malloc(), and the final free(huge) is safe because free(NULL) is defined to do nothing. That rule makes cleanup code shorter, and you should lean on it.

calloc: zeroed memory with a checked multiply

void *calloc(size_t count, size_t size) allocates count * size bytes, fails with NULL if the product overflows, and sets every byte to zero. Two points deserve attention.

First, all-bits-zero is the zero value for integers, but ISO C does not promise it is a null pointer or 0.0 for every type. In practice it is on every platform you will meet (x86-64, arm64, RISC-V), and POSIX requires it for pointers, but code that must be strictly portable initializes pointers and floating-point fields explicitly.

Second, calloc() is often cheaper than malloc() followed by memset() for large blocks. A big request is served by fresh pages from the kernel, which are already zero, so the library can skip the clearing and the memory is only faulted in when touched. A later post in this series explains the page-fault side of that.

zeroed.cc
#include <stdio.h>
#include <stdlib.h>

struct counter {
    long hits;
    long misses;
};

int main(void)
{
    struct counter *c = calloc(4, sizeof *c);

    if (c == NULL) {
        return EXIT_FAILURE;
    }
    c[2].hits++;
    for (int i = 0; i < 4; i++) {
        printf("slot %d: hits=%ld misses=%ld\n", i, c[i].hits, c[i].misses);
    }
    free(c);
    return EXIT_SUCCESS;
}
Text
slot 0: hits=0 misses=0
slot 1: hits=0 misses=0
slot 2: hits=1 misses=0
slot 3: hits=0 misses=0

Use calloc() whenever you want a zeroed table, and whenever you want the overflow check on an array size. Use malloc() when you are about to overwrite every byte anyway, such as copying a string into a new buffer.

realloc: resize, and the pitfall everyone hits

void *realloc(void *ptr, size_t size) changes the size of a block. If there is room after the block, it grows in place. If not, the library allocates a new block, copies the old contents, frees the old block and returns the new address. The old pointer is then invalid, whether or not the address happens to have changed, and you must continue with the returned value.

The pitfall is the failure case. When realloc() cannot satisfy the request it returns NULL and leaves the original block untouched and still allocated. The tempting one-liner overwrites your only pointer to it:

realloc_leak.cc
#include <stdlib.h>

int *grow_wrong(int *items, size_t new_count)
{
    items = realloc(items, new_count * sizeof *items);   /* wrong */
    return items;                      /* on failure the old block is leaked */
}

When realloc() returns NULL, items is overwritten with it and the original block can no longer be freed. The correct form uses a temporary:

realloc_ok.cc
#include <stdint.h>
#include <stdlib.h>

int grow(int **items, size_t new_count)
{
    int *tmp;

    if (new_count > SIZE_MAX / sizeof **items) {
        return -1;
    }
    tmp = realloc(*items, new_count * sizeof **items);
    if (tmp == NULL) {
        return -1;                     /* *items is still valid and owned */
    }
    *items = tmp;
    return 0;
}

The function takes a pointer to the caller's pointer, so a successful call updates it and a failed call leaves it alone. Two edge cases are worth knowing. realloc(NULL, n) is the same as malloc(n), which lets one code path handle the first allocation and all later growth. And realloc(p, 0) has varied across implementations: the standard calls it implementation-defined up to C17 and makes it undefined behavior in C23, so never use it as a roundabout free(). Call free() when you mean free.

glibc also provides reallocarray(ptr, count, size) since version 2.26, which is realloc() with the same overflow check calloc() has. It is not in ISO C, but it is in POSIX.1-2024, and it is the best tool for growing an array.

free: give it back, once

void free(void *ptr) releases a block that malloc(), calloc() or realloc() returned. The rules are short and strict:

  • Pass exactly the pointer the allocator returned, not a pointer into the middle of the block and not a pointer past it.

  • Free each block once. A second free() of the same address is undefined behavior.

  • Do not touch the block afterward, not to read, write or free.

  • free(NULL) does nothing and is always safe.

free() does not give memory back to the operating system, in general. It returns the block to the allocator, which keeps it for the next request. A process's resident size often stays high after a burst of frees for exactly that reason, and a later section covers when the memory is actually released. What matters now is that "freed" and "returned to the OS" are different things, and that a freed block is still addressable memory, which is what makes use-after-free bugs so quiet.

A habit that costs nothing and catches mistakes early: set a pointer to NULL right after freeing it when it lives on in a structure. A later free() of it is then harmless, and a later dereference crashes immediately at address zero instead of corrupting memory silently.

free_null.cc
#include <stdio.h>
#include <stdlib.h>

struct buffer {
    char *data;
    size_t len;
};

void buffer_release(struct buffer *b)
{
    free(b->data);
    b->data = NULL;       /* a second release is now a no-op */
    b->len = 0;
}

int main(void)
{
    struct buffer b = { malloc(64), 64 };

    buffer_release(&b);
    buffer_release(&b);   /* harmless: free(NULL) does nothing */
    printf("released twice, data=%p\n", (void *)b.data);
    return EXIT_SUCCESS;
}
Text
released twice, data=(nil)

The (nil) text is how glibc's printf renders a null pointer with %p; another C library may print 0x0 or (null).

The six classic mistakes

Almost every memory bug is one of six. Learn their shapes, because the compiler will not warn you about most of them and the symptoms show up far from the cause.

1. The leak

A block is allocated and never freed, usually because an early return skips the cleanup.

leak.cc
#include <stdio.h>
#include <stdlib.h>

int load(const char *path)
{
    char *buf = malloc(4096);

    if (buf == NULL) {
        return -1;
    }
    FILE *f = fopen(path, "r");
    if (f == NULL) {
        return -1;                     /* buf is leaked here */
    }
    fread(buf, 1, 4096, f);
    fclose(f);
    free(buf);
    return 0;
}

A leak in a short-lived program is harmless because the operating system reclaims everything at exit. In a server it is a slow death: memory use climbs until the process is killed. The fix is structural, covered under ownership below.

2. Use after free

The block is read or written after free(). The memory is still mapped, so the access usually succeeds and returns old or recycled data. The allocator may already have reused the block for something else, and your write silently corrupts the new owner.

3. Double free

Freeing the same pointer twice. glibc detects many cases and aborts with a message such as free(): double free detected in tcache 2 followed by Aborted (core dumped). The checks exist to catch bugs, but a double free is also an old attack primitive, so a program that triggers it is both buggy and exploitable.

4. Buffer overflow

Writing past the end of a block, often by one byte. The classic version forgets the terminating zero:

off_by_one.cc
#include <stdlib.h>
#include <string.h>

char *copy(const char *s)
{
    char *p = malloc(strlen(s));       /* wrong: no room for the terminator */

    if (p != NULL) {
        strcpy(p, s);                  /* writes strlen(s) + 1 bytes */
    }
    return p;
}

The write lands on the allocator's bookkeeping for the next block, and the crash appears later, inside malloc() or free(), with a message such as malloc(): corrupted top size or free(): invalid next size (fast). When the failing line is inside the allocator and your code looks fine, suspect an overflow earlier in the run. The fix is malloc(strlen(s) + 1), or better, strdup(s).

5. Freeing something that is not yours

Passing free() a stack address, a pointer into the middle of a block, a string literal, or memory from a different allocator. glibc reports free(): invalid pointer or munmap_chunk(): invalid pointer and aborts.

6. Reading uninitialized memory

Using a malloc() block's contents before writing them. It works by luck when the block was fresh from the kernel and fails when it was recycled. The symptom is nondeterministic output that changes with unrelated edits.

These six are why the next section matters more than any API detail.

Ownership: the rule that prevents the bugs

A pointer to heap memory has an owner, the one piece of code responsible for freeing it. Every bug above is a failure to keep that straight: nobody frees it (leak), two owners free it (double free), or someone keeps using it after the owner freed it. C has no way to express ownership in the type system, so you write it down in conventions and keep to them.

Four conventions that work in practice:

  1. The creator documents who frees. A function that returns a freshly allocated block says so in its comment, and the caller owns the result. Name such functions so the contract shows: parse_config() returns a new object, config_get() returns a borrowed pointer.

  2. Borrowed pointers are never freed and never outlive the owner. A function that receives a const char *name may read it and must not free it or keep it after returning, unless it copies it.

  3. Structures own their members. An object that holds pointers has a matching destroy function that frees every one of them, and the code that created the object calls it exactly once.

  4. Init and destroy come in pairs. If you wrote thing_new(), you write thing_free() in the same commit.

Here is a small type that follows all four. It owns a name and an array of scores.

player.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct player {
    char *name;            /* owned: copied in player_new, freed in player_free */
    int *scores;           /* owned */
    size_t count;
};

struct player *player_new(const char *name, size_t slots)
{
    struct player *p = calloc(1, sizeof *p);

    if (p == NULL) {
        return NULL;
    }
    p->name = strdup(name);
    p->scores = calloc(slots, sizeof *p->scores);
    if (p->name == NULL || p->scores == NULL) {
        free(p->name);
        free(p->scores);
        free(p);
        return NULL;
    }
    p->count = slots;
    return p;
}

void player_free(struct player *p)
{
    if (p == NULL) {
        return;
    }
    free(p->name);
    free(p->scores);
    free(p);
}

int main(void)
{
    struct player *p = player_new("ada", 3);

    if (p == NULL) {
        return EXIT_FAILURE;
    }
    p->scores[1] = 88;
    printf("%s has %zu slots, slot 1 = %d\n", p->name, p->count, p->scores[1]);
    player_free(p);
    return EXIT_SUCCESS;
}
Text
ada has 3 slots, slot 1 = 88

player_new() is written so that failure at any step cleans up what came before it, and free(NULL) makes the cleanup branch short, since a member that was never allocated is NULL thanks to calloc() zeroing the struct. The caller has one thing to remember, and that is to call player_free() once.

The single-exit cleanup pattern

When a function acquires several resources in sequence, a chain of if (...) { free(a); free(b); return -1; } blocks grows and rots. The idiom that scales is one cleanup label at the bottom, reached by goto from every failure point. It is one of the few uses of goto that most C style guides endorse, including the Linux kernel's.

cleanup.cc
#include <stdio.h>
#include <stdlib.h>

int process(const char *path)
{
    int rc = -1;
    char *line = NULL;
    int *table = NULL;
    FILE *f = NULL;

    line = malloc(256);
    if (line == NULL) {
        goto out;
    }
    table = calloc(100, sizeof *table);
    if (table == NULL) {
        goto out;
    }
    f = fopen(path, "r");
    if (f == NULL) {
        goto out;
    }
    if (fgets(line, 256, f) == NULL) {
        goto out;
    }
    rc = 0;                            /* success falls through to the cleanup */
out:
    if (f != NULL) {
        fclose(f);
    }
    free(table);
    free(line);
    return rc;
}

Every variable is initialized to NULL or an invalid value at the top, so the cleanup can run no matter how far the function got. There is one place where each resource is released, so adding a fourth resource means adding one variable and one line in the cleanup.

Growing buffers and arrays

The most common real use of realloc() is a buffer that grows as data arrives. Growing by a fixed amount each time makes the total work quadratic, because every growth may copy everything so far. The standard answer is geometric growth: double the capacity when full, so the number of reallocations is logarithmic and the amortized cost per append is constant.

vec.cc
#include <stdio.h>
#include <stdlib.h>

struct vec {
    int *data;
    size_t len;
    size_t cap;
};

int vec_push(struct vec *v, int value)
{
    if (v->len == v->cap) {
        size_t newcap = v->cap == 0 ? 4 : v->cap * 2;
        int *tmp = reallocarray(v->data, newcap, sizeof *v->data);

        if (tmp == NULL) {
            return -1;
        }
        v->data = tmp;
        v->cap = newcap;
    }
    v->data[v->len++] = value;
    return 0;
}

void vec_free(struct vec *v)
{
    free(v->data);
    v->data = NULL;
    v->len = v->cap = 0;
}

int main(void)
{
    struct vec v = {0};

    for (int i = 1; i <= 10; i++) {
        if (vec_push(&v, i * i) != 0) {
            vec_free(&v);
            return EXIT_FAILURE;
        }
    }
    printf("len=%zu cap=%zu last=%d\n", v.len, v.cap, v.data[v.len - 1]);
    vec_free(&v);
    return EXIT_SUCCESS;
}

Ten pushes grow the capacity 0, 4, 8, 16, so the program ends with a capacity of 16:

Text
len=10 cap=16 last=100

Note that a pointer into v.data taken before a push is invalid after it, because reallocarray() may have moved the block. If you must hold a reference to an element across pushes, hold its index.

Building strings

The same pattern applies to text. For formatted output of unknown length, snprintf() does the measuring for you: called with a zero-size buffer it returns the length that would be needed, excluding the terminator. Allocate that plus one, then format for real.

format.cc
#include <stdio.h>
#include <stdlib.h>

char *format_label(const char *name, int id)
{
    int need = snprintf(NULL, 0, "%s-%04d", name, id);
    char *out;

    if (need < 0) {
        return NULL;
    }
    out = malloc((size_t)need + 1);
    if (out != NULL) {
        snprintf(out, (size_t)need + 1, "%s-%04d", name, id);
    }
    return out;
}

int main(void)
{
    char *label = format_label("invoice", 42);

    if (label != NULL) {
        puts(label);
        free(label);
    }
    return 0;
}
Text
invoice-0042

asprintf() does both steps in one call on glibc and the BSDs, but it is a GNU extension (standardized only recently), so the two-step form above is the portable one. strdup() was added to ISO C in C23, and it has been in POSIX for decades.

Alignment and what the allocator really gives you

Every block malloc() returns is aligned to at least alignof(max_align_t), which is 16 bytes on x86-64 and arm64 Linux. That suits every standard type. Some hardware needs more, such as a 32-byte alignment for an AVX buffer or a 64-byte one to match a cache line. For those, aligned_alloc(alignment, size) (C11) and posix_memalign() exist, and a later post covers them in full.

The allocator also rounds up. glibc's malloc_usable_size(), declared in <malloc.h>, reports how many bytes a block really holds. It is a diagnostic tool, not something to build on, but it shows the overhead clearly:

usable.cc
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t sizes[] = { 1, 24, 25, 100, 1000 };

    for (size_t i = 0; i < sizeof sizes / sizeof *sizes; i++) {
        void *p = malloc(sizes[i]);
        printf("request %4zu -> usable %4zu\n", sizes[i], malloc_usable_size(p));
        free(p);
    }
    return 0;
}

On 64-bit glibc 2.40:

Text
request    1 -> usable   24
request   24 -> usable   24
request   25 -> usable   40
request  100 -> usable  104
request 1000 -> usable 1000

The smallest block has 24 usable bytes, and sizes step in units of 16 after that. The extra bytes are real: writing into them does not corrupt anything today, but nothing guarantees it, and code that relies on them breaks the day the allocator changes or a sanitizer is attached. The 8-byte header that sits before each block is what the arithmetic is spending, and it is also what an overflow tramples first.

What glibc does underneath

Understanding the implementation explains behaviors that otherwise look like bugs: why memory is not returned, why a one-byte allocation costs 32 bytes, and why a large allocation behaves differently from a small one.

Small requests come from the heap. The heap is a region of the process's address space that glibc grows with the brk() system call. malloc() carves blocks from it, and free() puts them on lists, called bins, sorted by size so that the next request of a similar size reuses them. Freed blocks next to each other are merged, so the heap does not fragment into dust. Recently freed small blocks go first into a per-thread cache, the tcache, which serves the next same-size request without any locking, and that is why a tight allocate-free loop is fast.

Large requests are mapped separately. A request at or above the mmap threshold, 128 KiB by default, is served by its own mmap() call, and free() unmaps it again with munmap(), returning the memory to the kernel immediately. The threshold adjusts upward dynamically as the program frees such blocks, up to a cap of 32 MiB on 64-bit systems. This is why freeing a huge buffer shrinks the process and freeing many small ones may not.

Threads get their own arenas. To avoid contention, glibc creates additional arenas, each with its own lock and heap, up to a limit proportional to the number of CPU cores. A thread picks one and sticks to it. A block freed by a different thread than allocated it goes back to its original arena, which is correct and sometimes slow.

The top of the heap can be trimmed. When the free space at the top of the brk heap exceeds the trim threshold (128 KiB by default), free() shrinks the heap with brk() and gives that memory back. Free space in the middle of the heap cannot be returned this way, so one long-lived small block near the top can pin hundreds of megabytes below it. This is the usual explanation when a service's memory climbs and never falls, and the later posts on malloc_trim and arena limits show what to do about it.

You can watch the system calls directly. Running strace -e trace=brk,mmap,munmap ./program on a program that allocates 10 bytes, then 1 MiB, shows the brk calls growing the heap for the first and an mmap call for the second, followed by munmap when it is freed.

Finding bugs

Reading code finds some of the six mistakes. Tools find the rest, and you should use them routinely rather than after a crash.

AddressSanitizer is the first tool to reach for. Compile with -fsanitize=address -g -O1 and run normally. It reports heap overflows, use after free, double free and invalid free, each with the allocation and free stack traces. A heap overflow produces a report that begins ERROR: AddressSanitizer: heap-buffer-overflow on address ... and names the line of the bad access and the line that allocated the block. It slows the program by roughly a factor of two and uses more memory, which is acceptable for tests. Add -fsanitize=undefined for the rest.

Valgrind's Memcheck needs no recompilation. valgrind --leak-check=full ./program reports invalid reads and writes, uses of uninitialized values and leaks, with a summary at exit such as definitely lost: 4,096 bytes in 1 blocks. It is slower than the sanitizer, typically by an order of magnitude, and it catches uninitialized reads that AddressSanitizer does not.

glibc's own checks need nothing at all. Setting MALLOC_PERTURB_=165 in the environment fills freed memory and new blocks with a pattern, so a program that reads uninitialized or freed memory misbehaves loudly instead of by luck. MALLOC_CHECK_=3 enables extra consistency checks in the older style, and the default abort messages already catch many corruptions at free() time.

**mtrace()** is the glibc-specific leak tracer, useful on a machine where you cannot install a sanitizer. Call mtrace() from <mcheck.h> at the start of main, set the environment variable MALLOC_TRACE to a file name, and run the program. The library logs every allocation and free to that file, and the mtrace script that ships with glibc turns the log into a list of blocks that were never freed, with the address of the code that allocated each one. It is slower and less precise than the other two tools, and its value is that it works anywhere glibc does, including a stripped-down embedded Linux image.

A short test routine we would put in every project: build the test suite once with AddressSanitizer and -fsanitize=undefined, and run it in continuous integration, with MALLOC_PERTURB_ set on the plain build as well. The two together catch a large majority of allocation bugs before they leave the developer's machine.

Patterns beyond plain malloc

General-purpose allocation is flexible, and flexibility costs: a header on every block, a search for a fit and bookkeeping that make malloc() slower and more fragmentation-prone than a purpose-built scheme. When the pattern of your allocations is known, a specialized allocator is simpler and faster.

Arena (bump) allocation. Allocate one big block and hand out pieces by moving an offset. Free everything at once by resetting the offset. It suits work with a clear phase boundary, such as parsing a request or building a compiler's syntax tree, because there is no per-object free() to forget. A later post builds one in full.

Pool allocation. For many objects of the same size, keep a free list of fixed-size slots. Allocation and release are a pointer swap, there is no fragmentation, and the memory is dense. A later post builds one.

Stack allocation for small, bounded buffers. If the size is small and has a known upper bound, a local array beats the heap on every measure. Variable length arrays and alloca() extend that to run-time sizes, and both risk overflowing the stack on a large or hostile size, so we avoid them for anything influenced by input.

No allocation at all. Embedded firmware, interrupt handlers and real-time loops often forbid malloc() after startup, because its running time is not bounded and its failure mode is not acceptable. They use static buffers sized at compile time. If that describes your target, the section on allocators in the embedded posts of this series is the place to go next.

When dynamic allocation is the wrong tool

Heap allocation earns its cost when size or lifetime is unknown at compile time. It is a poor choice when the size is small and fixed (use the stack or a static), when allocation sits in a hot loop (hoist it out, or use a pool), when you need hard real-time guarantees (preallocate), and when a failure must not be possible (allocate everything at startup, where failure is easy to handle). Reaching for malloc() out of habit is also how programs end up with thousands of tiny blocks where one array would do, with all the header overhead and cache misses that implies.

A worked example: reading lines of any length

Pulling the pieces together, here is a function that reads a whole line from a stream with no fixed limit, using geometric growth, a temporary for realloc(), a single owner and a documented contract. This is the function that getline() implements in POSIX, and writing it once shows each rule at work.

readline.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a newly allocated, NUL-terminated line without the newline.
   The caller owns the result and frees it. Returns NULL at end of input
   or on allocation failure. */
char *read_line(FILE *in)
{
    size_t cap = 16, len = 0;
    char *buf = malloc(cap);
    int c;

    if (buf == NULL) {
        return NULL;
    }
    while ((c = fgetc(in)) != EOF && c != '\n') {
        if (len + 1 >= cap) {
            size_t newcap = cap * 2;
            char *tmp = realloc(buf, newcap);

            if (tmp == NULL) {
                free(buf);
                return NULL;
            }
            buf = tmp;
            cap = newcap;
        }
        buf[len++] = (char)c;
    }
    if (c == EOF && len == 0) {
        free(buf);
        return NULL;
    }
    buf[len] = '\0';
    return buf;
}

int main(void)
{
    char *line;
    int n = 0;

    while ((line = read_line(stdin)) != NULL) {
        printf("%d: %zu chars: %s\n", ++n, strlen(line), line);
        free(line);
    }
    return 0;
}

Fed two lines, short and a line that is much longer than the starting capacity, through standard input:

Text
1: 5 chars: short
2: 49 chars: a line that is much longer than the starting capacity

Walk through it against the rules. The buffer starts at 16 bytes and doubles, so the second line forces two reallocations (16 to 32 to 64). Each realloc() result goes into tmp, and on failure the old buffer is freed before returning, so nothing leaks. The function reserves space for the terminator with len + 1 >= cap. The caller owns each returned line and frees it inside the loop. And a trailing partial line with no final newline is still returned, since the check for end of input requires len == 0.

Reading an AddressSanitizer report

The first time a sanitizer report appears, it looks like noise. It is a short story told in three parts, and once you know the order it takes a minute to read. Take the off-by-one copy from earlier, built into a program that calls it:

asan_demo.cc
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *p = malloc(5);

    strcpy(p, "hello");        /* needs 6 bytes with the terminator */
    free(p);
    return 0;
}

Compile with gcc -fsanitize=address -g -O1 -o asan_demo asan_demo.c and run it. The report begins like this (addresses and the process id differ on every run, so treat them as examples):

Text
==4127==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000015 at pc 0x55d4a1b3c2f1 bp 0x7ffd1c2e4a60 sp 0x7ffd1c2e4220
WRITE of size 6 at 0x602000000015 thread T0
    #0 0x55d4a1b3c2f0 in main asan_demo.c:7
0x602000000015 is located 0 bytes after 5-byte region [0x602000000010,0x602000000015)
allocated by thread T0 here:
    #0 0x7f1c8a2d9a37 in malloc
    #1 0x55d4a1b3c2ba in main asan_demo.c:6

Read it in three steps. The first line names the bug class, heap-buffer-overflow, and the access: a write of 6 bytes. The stack under it points at the exact source line that did the damage, line 7. The "is located 0 bytes after 5-byte region" line is the most useful one: it says your write started exactly at the end of a 5-byte block, which is the signature of a missing terminator byte, and the "allocated by" stack points at line 6, where the undersized block was created. Other classes read the same way. A heap-use-after-free report adds a third stack, "freed by thread T0 here", so you see the allocation, the release and the stale access, and the bug is the gap between the last two.

Structures with a variable-length tail

One allocation can hold a header and its payload together, which halves the number of blocks to manage and keeps the data contiguous. C99 added the flexible array member for this: the last member of a struct is declared without a size.

flexible.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct message {
    size_t len;
    char text[];               /* flexible array member */
};

struct message *message_new(const char *s)
{
    size_t n = strlen(s);
    struct message *m = malloc(sizeof *m + n + 1);

    if (m == NULL) {
        return NULL;
    }
    m->len = n;
    memcpy(m->text, s, n + 1);
    return m;
}

int main(void)
{
    struct message *m = message_new("one allocation, header and text");

    if (m != NULL) {
        printf("%zu: %s\n", m->len, m->text);
        free(m);
    }
    return 0;
}
Text
31: one allocation, header and text

sizeof *m covers the fixed part only, so the size request adds the tail by hand, plus one for the terminator. The whole message is freed with a single free(). The restrictions are real: the struct cannot be an array element or a member of another struct in ordinary C, and copying it by assignment copies only the header. Use it for network packets, variable-length records and strings with a length prefix.

Threads, fork and signals

malloc() and free() are thread-safe on every mainstream system, so threads may allocate and free concurrently, and a block may be freed by a different thread than the one that allocated it. What is not safe is sharing a pointer without synchronization: two threads that both think they own a block free it twice. Ownership rules apply across threads exactly as within one.

Two situations need care. First, malloc() and free() are not async-signal-safe, so a signal handler must not call them. The allocator may be midway through updating its lists when the signal arrives, and a handler that re-enters it can deadlock or corrupt the heap. A handler should set a flag and let the main loop do the work. Second, after fork() in a multithreaded program, the child has only the calling thread, and any lock another thread held at the time of the fork is held forever in the child. glibc handles its own allocator locks across fork(), but a child that then calls functions of other libraries that allocate under their own locks can hang. The conventional rule is to call only async-signal-safe functions between fork() and exec() in a multithreaded process.

Out of memory, overcommit and the killer

On a default Linux system, malloc() of a few gigabytes succeeds on a machine with a few gigabytes free, because the kernel's heuristic overcommit mode (/proc/sys/vm/overcommit_memory set to 0) refuses only requests that are obviously impossible. Pages are committed on first touch, and if the system runs out then, the kernel's out-of-memory killer picks a process and ends it with SIGKILL. No NULL return warns you, and no handler runs.

So allocation failure on Linux comes in two forms. The polite one, a NULL from malloc(), comes from address-space limits, container limits and mode 2 (strict) overcommit. The impolite one, the kill, comes from touching pages that do not exist. A program that must survive low memory should touch what it allocates early, at startup, so the killer, if it comes, comes before important work starts, and should size its caches against the container's memory limit read from the cgroup files.

Testing the failure paths

Cleanup code on error paths is the least-tested code in any C program, because allocation almost never fails in a test. You can force it to. Wrap the allocator behind a function that fails on the Nth call, and run the code under test for every N from 1 until it finishes without a failure.

failtest.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int fail_at = 0;     /* 0 means never fail */
static int calls = 0;

static void *test_malloc(size_t n)
{
    if (fail_at != 0 && ++calls == fail_at) {
        return NULL;
    }
    return malloc(n);
}

struct pair { char *a; char *b; };

static struct pair *pair_new(void)
{
    struct pair *p = test_malloc(sizeof *p);

    if (p == NULL) {
        return NULL;
    }
    p->a = test_malloc(16);
    p->b = test_malloc(16);
    if (p->a == NULL || p->b == NULL) {
        free(p->a);
        free(p->b);
        free(p);
        return NULL;
    }
    return p;
}

int main(void)
{
    for (fail_at = 1; fail_at <= 4; fail_at++) {
        struct pair *p;

        calls = 0;
        p = pair_new();
        printf("fail allocation %d: %s\n", fail_at, p ? "built" : "clean failure");
        if (p != NULL) {
            free(p->a);
            free(p->b);
            free(p);
        }
    }
    return 0;
}
Text
fail allocation 1: clean failure
fail allocation 2: clean failure
fail allocation 3: clean failure
fail allocation 4: built

The function makes three allocations, so failing the first, second or third must return NULL without leaking, and failing a fourth, which never happens, builds the object. Run this under AddressSanitizer or Valgrind, and any leak on the failure paths is reported. In pair_new(), p->a and p->b are uninitialized if the struct came from malloc(), so the code above leans on both being assigned before the check; if you add a step between, start from calloc() so unset members are NULL. For larger programs, the same idea works without a wrapper by using the LD_PRELOAD interposition technique, but a wrapper in your own tests is simpler.

A checklist before you commit

When you review code that allocates, or write it, run through these questions.

  1. Is every malloc(), calloc() and realloc() result checked for NULL?

  2. Is the size computed from sizeof *p, and is any multiplication checked for overflow?

  3. Does every realloc() go through a temporary?

  4. For each allocation, can you name the owner and the line that frees it?

  5. On every error path, is everything allocated so far released, once?

  6. After free(), is the pointer dead or set to NULL?

  7. Do you allocate strlen(s) + 1 for strings, not strlen(s)?

  8. Have the tests run once under AddressSanitizer?

If all eight answers are yes, the code is in better shape than most C in production.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.