Understanding memory mistakes
Diagnose invalid access through lifetime, bounds, type, initialization, and ownership instead of guessing whether code will crash.
In this chapter9 sections
A pointer can look plausible and still be invalid for an operation. Memory mistakes often come from crossing a boundary, using an object after its lifetime ends, or losing track of ownership. We will name these failures and connect them to the rule they break.
1. Valid access needs several facts at once
| Question | What to establish |
|---|---|
| Which object? | The pointer or expression actually designates the intended object. |
| Alive? | Its lifetime has begun and has not ended. |
| In range? | The operation stays within permitted array or object bounds. |
| Suitable access? | Alignment, effective type, initialization, and mutability rules are respected. |
| Who releases it? | An allocation has a consistent ownership and cleanup contract. |
These questions complement each other. A null check cannot prove that the target is alive or in range. A large enough allocation cannot prove the bytes represent an initialized value of the type you read. A cast cannot make an ended lifetime restart. A successful test on one input cannot establish every precondition for every execution.
2. Check a bound before forming an invalid access
int values[3] = {4, 5, 6};
size_t count = sizeof values / sizeof values[0];
size_t index = 2;
int selected = 0;
if (index < count) {
selected = values[index];
}
The check precedes subscripting. For pointer arithmetic, do the reasoning before forming an out-of-range pointer too. Do not write beyond an array and then use a later condition as evidence of safety. The last element index is count minus one for a nonempty array; a one-past pointer represents a boundary, not spare storage.
Off-by-one errors often come from confusing capacity with the last index, or string length with required storage. A string of length three needs a fourth element for its terminator. An array of three integers has no fourth integer merely because neighboring memory can be addressed on the machine.
3. A stale alias is not a second chance
int *owner = malloc(sizeof *owner);
if (owner == NULL) {
return EXIT_FAILURE;
}
int *borrowed = owner;
*borrowed = 9;
int saved_value = *borrowed;
free(owner);
owner = NULL;
borrowed = NULL;
The value is copied while the object is alive. After free, neither old pointer value is read; each pointer object is assigned a fresh null value. Setting only owner to null would not automatically change borrowed. Real interfaces must prevent outstanding borrowers from accessing an ended object, rather than relying on one owner variable being reset.
Using an allocation after release is use-after-free. Releasing it again is double free. C does not promise a particular error message for either. A successful realloc also retires pointers to the old allocation, even when the returned pointer has the same apparent address. Retain needed data or offsets before replacement, then rebuild valid access from the new result.
4. Return a result with a valid lifetime
#include <assert.h>
static int make_score(void)
{
int local = 7;
return local;
}
int main(void)
{
int score = make_score();
assert(score == 7);
return 0;
}
Returning the integer value copies the result before the local object’s lifetime ends. Returning the address of that ordinary local object would not keep it alive. Other interface choices include writing into a valid caller-provided object, returning an owned allocation with a release contract, or deliberately using a static object with documented sharing behavior. Choose the lifetime first; then choose the pointer syntax.
5. Leaks are about unreleased responsibility
Losing the last usable reference to an allocation can make release impossible for the program. Overwriting an owning pointer directly with a failed realloc result is a common example. Leaks can also involve allocations that remain reachable but are retained without a useful lifetime policy. A raw pointer’s presence is not proof that cleanup will happen.
Common hosted operating systems reclaim a process’s resources when it terminates, but that is not a universal C memory-management rule, and it does not help a long-running program before termination. Similarly, freeing an allocation may make storage reusable by its allocator without immediately shrinking the process’s physical memory use. Reason about allocation lifetimes rather than a single “heap grows” picture.
6. Tools support reasoning; they do not replace it
Compiler diagnostics can expose suspicious conversions, missing declarations, and some invalid accesses. Runtime memory instrumentation can find many errors on the paths it executes. A clean run does not prove an unexecuted path safe. Some defects are violations of language rules even when a particular machine appears to tolerate them.
Use small cases that exercise empty input, one element, the last valid element, maximum accepted sizes, and failure cleanup. Keep deliberately invalid examples out of normal runnable code: describe the violated rule and never promise a specific output for undefined behavior. The examples in this unit demonstrate valid patterns; they do not execute use-after-free or an out-of-bounds access as a guessing exercise.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.4p2, 6.5, 6.5.6, 7.22.3. These stable rules support the C17 baseline; this draft is not the final ISO publication.
Before you move on
- Bounds, lifetime, type, and ownership failures are different memory mistakes.
- A non-null pointer can still be invalid for the requested access.
- Diagnostic tools provide evidence for exercised cases rather than a proof of all possible executions.
Keep these ideas separate
- Freeing one pointer / Repairing aliases
- Releasing a target or clearing one pointer does not repair other pointers that referred to the same storage.
Which checks would distinguish a buffer overrun from a use-after-free in a small failing example?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- No. Other pointer objects do not update automatically.
✓ Correct reasoning. Ownership and alias lifetimes need a contract; clearing one pointer only changes that pointer object.
- Yes, free finds and clears all aliases.
free releases allocated storage; it does not locate and rewrite all pointer objects.
- Yes, NULL releases the same allocation again.
Assigning NULL is an assignment, not another deallocation operation.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.