Skip to content

Owners and Borrowers

The Course
•
40 min study

A pointer is just an address, and C lets you copy addresses freely. Pass one to a function, store it in a struct, keep a second copy in a local variable: now three pointers refer to one block. When the work is done, exactly one of them must be passed to free. If none is, the block leaks. If two are, the program frees the same block twice, which is undefined behavior and can corrupt the allocator. The language has no rule to settle this, so you make one: ownership.

The owner is the one pointer (or struct, or function) responsible for releasing an allocation. A borrower uses the same storage without that responsibility. A borrower must never free the block, and must stop using it once the owner releases it.

Predict and run

Read the program before pressing Run. Write down its output and explain which pointer is the owner.

Predict before running C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *owner = malloc(sizeof *owner);
    if (owner == NULL) { return 1; }
    *owner = 25;
    const int *borrowed = owner;
    printf("%d\n", *borrowed);
    free(owner);
    owner = NULL;
    return 0;
}
Check your prediction
Text
25

owner received the block from malloc, so it is the one passed to free. borrowed is declared const int *, which documents that it only reads. The last use of borrowed comes before the free, so every access is valid.

Copying a pointer does not copy the data

Two pointers to one block see each other's changes, because there is only one block:

Two names, one object C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *owner = malloc(2 * sizeof *owner);
    if (owner == NULL) { return 1; }
    owner[0] = 25;
    owner[1] = 40;
    const int *view = owner;
    owner[1] = 45;
    printf("view sees %d and %d\n", view[0], view[1]);
    free(owner);
    return 0;
}
Text
view sees 25 and 45

This is useful: a function can borrow a large array without copying it. It is also the source of the main lifetime rule. A borrowed pointer is valid only while the owner's block is alive and unchanged in location.

After free, every alias is dead

free(owner) ends the lifetime of the block. Every pointer into it now dangles, even though the pointer variables still hold the old address. Using one is a use-after-free:

C
int *owner = malloc(sizeof *owner);
const int *borrowed = owner;
free(owner);
owner = NULL;
printf("%d\n", *borrowed);   /* undefined: the block is gone */

Setting owner = NULL protects only that variable. borrowed still holds the old address, and nothing in C tracks it. The program might print 25, print garbage, or crash, and the result can change between runs and compilers. Never use such output as a prediction. Build with AddressSanitizer (-fsanitize=address) locally and it stops at the bad read:

Shell
ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010
READ of size 4 at 0x602000000010 thread T0

A double free, calling free twice on the same block (or once on the owner and once on a borrower), is the same kind of bug. AddressSanitizer reports it as attempting double-free.

Fix: the owner that was overwritten

A use-after-free cannot be shown reliably in a browser run, but its sibling, the leak, can, if the program counts its own blocks. Here make_counts and release keep a live count of blocks allocated and not yet freed. The program should end with live at end: 0. Run it and find the line that loses a block.

Fix: the lost block C
#include <stdio.h>
#include <stdlib.h>

static int live = 0;   /* blocks allocated and not yet freed */

int *make_counts(size_t n) {
    int *data = calloc(n, sizeof *data);
    if (data != NULL) { ++live; }
    return data;   /* the caller owns the block */
}

void release(int *data) {
    if (data != NULL) { --live; free(data); }
}

int main(void) {
    int *counts = make_counts(3);
    if (counts == NULL) { return 1; }
    counts[0] = 25;
    printf("first block: %d\n", counts[0]);
    counts = make_counts(5);   /* start over with a bigger block */
    if (counts == NULL) { return 1; }
    printf("second block: %d\n", counts[0]);
    release(counts);
    printf("live at end: %d\n", live);
    return 0;
}
Shell
first block: 25
second block: 0
live at end: 1
Check your fix

counts = make_counts(5); overwrites the only pointer to the first block. Nothing can free it after that line, so it leaks, and the count ends at 1. Assigning a new block to an owner is fine only when the owner holds nothing; here the old block must be released first:

C
#include <stdio.h>
#include <stdlib.h>

static int live = 0;   /* blocks allocated and not yet freed */

int *make_counts(size_t n) {
    int *data = calloc(n, sizeof *data);
    if (data != NULL) { ++live; }
    return data;   /* the caller owns the block */
}

void release(int *data) {
    if (data != NULL) { --live; free(data); }
}

int main(void) {
    int *counts = make_counts(3);
    if (counts == NULL) { return 1; }
    counts[0] = 25;
    printf("first block: %d\n", counts[0]);
    release(counts);           /* the old block's owner gives it up first */
    counts = make_counts(5);   /* start over with a bigger block */
    if (counts == NULL) { return 1; }
    printf("second block: %d\n", counts[0]);
    release(counts);
    printf("live at end: %d\n", live);
    return 0;
}
Text
first block: 25
second block: 0
live at end: 0

Leaks: losing the only owner

The opposite mistake is to lose the owner while the block is still allocated:

C
int *data = malloc(4 * sizeof *data);
data = malloc(8 * sizeof *data);   /* the first block now has no owner */

Nothing points to the first block any more, so nothing can free it. One leak is harmless in a short program, but a leak inside a loop that runs for every input line grows without limit. LeakSanitizer and Valgrind report blocks that were never freed.

Ownership can move

Ownership is not tied to the function that called malloc. A function that returns a freshly allocated pointer transfers ownership to its caller, and its contract must say so: "returns a new block; the caller frees it." The function keeps no copy, so after it returns, the caller is the only owner. Naming helps: in this course, functions that create a block the caller must release use make_ or copy_, and an owning struct has a matching _destroy function.

Practice

Exercise

Your turn

Write char *copy_topic(const char *topic) that returns a new heap copy of a string, including its null terminator, or NULL if topic is NULL or allocation fails. The caller owns the copy. In main, copy "reading", change the copy's first letter to R, print both strings, free the copy, and check the NULL case. Expected output: original: reading, copy: Reading, copy of NULL: NULL.

Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Write copy_topic here. The caller frees the result. */

int main(void) {
    const char *original = "reading";
    // Copy, modify the copy, print both, free the copy.
    return 0;
}
Hint 1: the idea

A string of strlen(topic) characters needs one more byte for the '\0' that ends it. Copying only the visible characters produces a buffer that printf reads past.

Hint 2: a first step

Before you allocate, decide the size on paper for "reading": how many characters does strlen count, and how many bytes must the copy hold? Write the NULL check and the allocation of that size, then copy, and check the terminator came along by printing the copy.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a new heap copy of topic, or NULL. The caller frees it. */
char *copy_topic(const char *topic) {
    if (topic == NULL) { return NULL; }
    size_t bytes = strlen(topic) + 1;
    char *copy = malloc(bytes);
    if (copy == NULL) { return NULL; }
    memcpy(copy, topic, bytes);
    return copy;
}

int main(void) {
    const char *original = "reading";
    char *copy = copy_topic(original);
    if (copy == NULL) { return 1; }
    copy[0] = 'R';
    printf("original: %s\n", original);
    printf("copy: %s\n", copy);
    free(copy);
    printf("copy of NULL: %s\n", copy_topic(NULL) == NULL ? "NULL" : "allocated");
    return 0;
}
Text
original: reading
copy: Reading
copy of NULL: NULL

The copy is a separate block, so changing it leaves the string literal alone; modifying a string literal itself would be undefined behavior. sizeof(char) is 1 by definition, so bytes is already a byte count, and strlen plus 1 cannot overflow for a string that exists in memory. main is the owner from the moment copy_topic returns, and it frees the copy exactly once. The checkpoint next wraps an owned block and its length into one struct.

Was this article helpful?

Your response is saved on this device.