Ownership, resizing, and failure

Lesson 9 of 14 · C memory foundations

An ownership contract says who releases an allocation and when. A borrowed pointer grants access without transferring responsibility. These are design rules, not types enforced by C. If a function returns a newly allocated string, document that the caller owns it; on failure, return null and leave no partially owned allocations behind.

owner ───> [ buffer ] <─── borrower
free by owner ──> lifetime ends; both pointers lose access

A structure owning both itself and a separate buffer must release the buffer first, then the structure. If allocating the second part fails, free the first part. A shallow copy of the structure duplicates the pointer, not the allocation; two apparent owners can cause a double free. Decide whether to transfer, duplicate, or share ownership explicitly.

realloc can resize a dynamic allocation. For a nonzero requested size, failure returns null and leaves the old allocation valid. On success, the old allocation’s lifetime ends even if the returned address appears unchanged; use the returned pointer and recompute interior pointers. Preserve the old pointer until success:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *p = malloc(2 * sizeof *p);
    if (!p) return 1;
    p[0] = 5; p[1] = 6;
    int *next = realloc(p, 3 * sizeof *p);
    if (!next) { free(p); return 1; }
    p = next;
    p[2] = 7;
    printf("%d %d %d\n", p[0], p[1], p[2]);
    free(p);
    return 0;
}

Successful output is 5 6 7. New bytes are uninitialized. Handle size zero separately rather than relying on version-dependent realloc(p, 0) behavior. Check overflow before computing the byte count. Allocation failure tests and sanitizers can reveal mistakes, but cannot prove a program correct.

Chapter index · Course index