YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Memory & dataChapter 29 of 73

Understanding memory mistakes

Diagnose invalid access through lifetime, bounds, type, initialization, and ownership instead of guessing whether code will crash.

6 min readFoundationsC17 baseline
Offline reading
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

QuestionWhat 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

C17 · illustrative fragment
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

C17 · illustrative fragment
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

Complete C17 program
#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

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.
Explain it in your own words

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.

Does assigning NULL to one pointer repair every alias after free?
Read the explanation for every choice
  1. 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.

  2. Yes, free finds and clears all aliases.

    free releases allocated storage; it does not locate and rewrite all pointer objects.

  3. 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.

CHAPTER 29 / 73

In this chapter

Understanding memory mistakes

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping