Pointers & Memory · intermediate · ~10 min

free and ownership

Identify one owner and release an allocation exactly once after its last use.

Overview

An allocation needs a clear cleanup responsibility. free ends that allocation's lifetime; it does not find or update every pointer that referred to it. This lesson connects allocation, use, and cleanup in one short function before introducing larger data structures.

Core concepts

Call free with NULL or with the allocation's base pointer that is still owned and has not already been freed. Do not free a local array, an interior pointer, or a borrowed string literal.

A borrowed pointer may be used only while its owner keeps the object alive. Setting one pointer to NULL after free can prevent reuse through that variable; it does not repair other aliases.

Write cleanup paths alongside allocation paths. Returning a computed value after cleanup is fine; returning a pointer into the freed block is not.

Lesson

An allocation needs a clear cleanup responsibility. free ends that allocation's lifetime; it does not find or update every pointer that referred to it. This lesson connects allocation, use, and cleanup in one short function before introducing larger data structures.

Code examples

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *owner = malloc(sizeof *owner);
    if (owner == NULL) return 1;
    *owner = 42;
    int answer = *owner;
    free(owner);
    owner = NULL;
    printf("%d\n", answer);
    return 0;
}

Expected output on a successful allocation, where applicable:

42

Line by line

answer is a separate integer copy made before cleanup. Printing it does not access the released allocation. Clearing owner affects only that variable, not hypothetical aliases.

Practice tasks

  1. Mark the last access to the allocation in the example.
  2. Solve Allocate, use, free.
  3. Solve Concatenate two arrays; the inputs are borrowed and the returned block is owned by the caller.
  4. Save linked-list cleanup for after structs and linked-list traversal.

Summary

Release an owned allocation once, after its last use. Copies of its pointer become invalid too. A NULL assignment does not extend an object's lifetime or repair aliases.

Practice with these exercises