Pointers & Memory · intermediate · ~10 min
Identify one owner and release an allocation exactly once after its last use.
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.
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.
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.
#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
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.
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.