Skip to content
systemcoding.dev
Systems Programming

Define Clear Ownership Rules for Heap Memory in C Functions

Decide who frees every heap block in C by naming owners and borrowers, marking transfers in function contracts, and following a few conventions that stop leaks.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the C, GNU and C++ logos.

C has no garbage collector and no destructor that runs on its own, so the only thing that stops a leak or a double free is a shared understanding of who is responsible for each block of heap memory. That understanding is called ownership. Rust encodes it in the type system, and C leaves it to you, to your function comments and to the habits of the team. When the habits are missing, the symptoms are the ones everyone has met: a server whose memory grows for days, a crash inside free() that shows up three functions away from the real bug, and a function nobody dares to touch because nobody knows whether it frees its argument.

This post gives the vocabulary, four rules for function boundaries, the naming and comment conventions that make the rules visible, and the cases that trip people up: out-parameters, containers, callbacks and failure paths. The examples are C17 compiled with GCC 14 against glibc 2.40.

The vocabulary

Three terms cover everything.

  • Owner. The one piece of code responsible for freeing a block. At any moment a live block has exactly one owner. A variable, a structure field or a function's frame can be an owner.

  • Borrower. Code that uses a block it does not own. It may read or write through the pointer for a limited time, and it must not free the block or keep the pointer after the owner may have released it.

  • Transfer. A moment when responsibility moves from one owner to another: a function returns a new block, a caller hands a block to a container, or a function takes over its argument. A transfer must be written in the contract. If it is only in someone's head, it will be got wrong.

The invariant to defend is simple: every block has exactly one owner, and the owner frees it exactly once. All the conventions below exist to make that checkable by reading the code.

Rule 1: say it in the function's contract

Every function that touches heap memory should answer, in a comment above it, one of four questions about each pointer it handles.

SituationContract
Returns a pointer to a new blockThe caller owns it and must free it
Returns a pointer into something that already existsA borrowed pointer, valid only while the owner lives
Takes a pointer and only reads or writes through itBorrowed for the duration of the call
Takes a pointer and keeps or frees itOwnership transfers into the function

Write it where the reader looks:

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

/* Returns a newly allocated copy of `s`. The caller owns the result and
   must free() it. Returns NULL if memory runs out. */
char *name_copy(const char *s)
{
    return strdup(s);
}

/* Returns a pointer to the first character after the last '/' in `path`.
   Borrowed: it points into `path` and is valid only as long as `path` is. */
const char *name_basename(const char *path)
{
    const char *slash = strrchr(path, '/');
    return slash != NULL ? slash + 1 : path;
}

The two functions differ in one word of the comment and a world of consequence. Freeing the result of name_basename() would call free() on the middle of a block and abort the program, and never freeing the result of name_copy() leaks. The const qualifier helps a little: returning const char * signals "do not modify, and probably do not free", though const is not a guarantee of anything about ownership.

Rule 2: make the name carry the contract

A convention works better when the function's name signals it, so a reader sees the contract at the call site without opening the declaration. Pick a scheme and apply it everywhere. A common one:

  • thing_new() or thing_create() returns a block the caller owns. Its partner is thing_free() or thing_destroy().

  • thing_get_x() or thing_x() returns a borrowed pointer.

  • thing_take_x() takes ownership of its argument.

  • thing_dup_x() returns a fresh copy, owned by the caller.

The project can choose other words, and what matters is that a _new never returns a borrowed pointer and a _get never returns something that needs freeing. The standard library follows the same instinct inconsistently: strdup() returns a block you free, getenv() returns a pointer into the environment you must not, and the names alone do not tell you which. When you write your own API, be more consistent than the standard library.

Rule 3: containers own what they hold

A structure that stores pointers to heap blocks is the owner of those blocks, and its destroy function releases them. Callers then never free an element they put into the container.

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

struct list {
    char **items;       /* owned: the array and every string in it */
    size_t count;
    size_t cap;
};

/* Copies `s` into the list. The list owns the copy; the caller keeps `s`. */
int list_add_copy(struct list *l, const char *s)
{
    if (l->count == l->cap) {
        size_t newcap = l->cap == 0 ? 4 : l->cap * 2;
        char **tmp = realloc(l->items, newcap * sizeof *tmp);

        if (tmp == NULL) {
            return -1;
        }
        l->items = tmp;
        l->cap = newcap;
    }
    l->items[l->count] = strdup(s);
    if (l->items[l->count] == NULL) {
        return -1;
    }
    l->count++;
    return 0;
}

/* Takes ownership of `s`: the caller must not free or use it afterward. */
int list_add_take(struct list *l, char *s)
{
    if (l->count == l->cap) {
        size_t newcap = l->cap == 0 ? 4 : l->cap * 2;
        char **tmp = realloc(l->items, newcap * sizeof *tmp);

        if (tmp == NULL) {
            return -1;          /* on failure the caller still owns `s` */
        }
        l->items = tmp;
        l->cap = newcap;
    }
    l->items[l->count++] = s;
    return 0;
}

void list_destroy(struct list *l)
{
    for (size_t i = 0; i < l->count; i++) {
        free(l->items[i]);
    }
    free(l->items);
    memset(l, 0, sizeof *l);
}

int main(void)
{
    struct list l = {0};
    char *built = malloc(16);

    strcpy(built, "taken string");
    list_add_copy(&l, "copied string");
    list_add_take(&l, built);        /* built now belongs to the list */

    for (size_t i = 0; i < l.count; i++) {
        printf("%zu: %s\n", i, l.items[i]);
    }
    list_destroy(&l);                /* frees both strings and the array */
    return 0;
}
Text
0: copied string
1: taken string

The two add functions show the two kinds of handoff side by side. list_add_copy() leaves the caller's string alone and makes the list a copy it owns. list_add_take() is cheaper, since it avoids a copy, and it carries a rule that the comment states: after the call the caller must not free or touch s. Note what happens on failure. list_add_take() returns -1 and the caller still owns s, because ownership transfers only on success. That asymmetry must be documented, as every caller needs to know which side owns the block after an error. We prefer to make failed transfers leave things as they were.

One main() line tells the story: list_destroy(&l) frees everything, and the program never calls free(built), because it gave that block away.

Rule 4: one failure path, owned by the allocator of record

A function that allocates several things must free what it has built if a later step fails. The pattern that keeps this correct is to initialize every pointer to NULL, jump to a single cleanup label on error, and give away the result only at the end. When the function finally succeeds, it transfers the finished object to the caller and sets its local pointer to NULL so the cleanup does not free it.

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

struct config {
    char *name;
    char *path;
};

/* Returns a new config the caller owns, or NULL on failure. */
struct config *config_new(const char *name, const char *path)
{
    struct config *c = NULL;
    char *n = NULL, *p = NULL;

    c = calloc(1, sizeof *c);
    n = strdup(name);
    p = strdup(path);
    if (c == NULL || n == NULL || p == NULL) {
        goto fail;
    }
    c->name = n;                /* ownership moves into the struct */
    c->path = p;
    return c;                   /* ownership moves to the caller */

fail:
    free(n);
    free(p);
    free(c);
    return NULL;
}

The fields are assigned only after every allocation succeeded, so the failure path never frees something the struct also owns. If it did assign first, the failure path would free the strings and then the caller would free them again through the struct.

Common traps

Out-parameters. A function that fills in char **out should say whether the caller owns *out on success, and what *out holds on failure. We set it to NULL on failure so a caller who frees it unconditionally is safe.

Callbacks. A function that takes a callback and a void *user_data should say whether it owns the data. If it does, it should also take a destructor, or the callback is the only code that knows how to release it.

Returning internal buffers. A function that returns a pointer to a static buffer is a borrowed pointer that the next call overwrites, which strerror() and asctime() do. Document it, and prefer an API that makes the caller supply the buffer.

Reallocating while borrowed. A borrowed pointer into a growing array becomes dangling when the array moves. The rule that avoids this is simple: do not hold pointers into a container across calls that may grow it. Hold an index.

How to check your rules

Rules on paper need a test. Build the program under AddressSanitizer with leak detection, which reports blocks nobody freed and stack traces of where they were made, and with Valgrind's summary:

Text
==5521== LEAK SUMMARY:
==5521==    definitely lost: 16 bytes in 1 blocks

A "definitely lost" line points at a block with no owner left, and its allocation stack names the function that created it. Match that function's contract against its callers, and the missing free() is usually in a caller that treated an owned result as borrowed. The reverse bug, a double free, shows as a free(): double free detected abort, and means two owners believed they were responsible.

Also inDebugging
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.