Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 135 ยท Pointers

The restrict Qualifier

Learn what pointer aliasing is, how the C99 restrict qualifier lets compilers optimize, the exact promise you make, and how memcpy, memmove and your own functions use it.

Two pointers alias when they refer to overlapping memory. Most of the time that is harmless, but it forces the compiler to be pessimistic: after writing through one pointer, it must assume that any value it read through the other might have changed. That caution costs speed, especially in loops over arrays, where the compiler would like to keep values in registers or process several elements at once.

C99 added the restrict qualifier so you can tell the compiler "these pointers never overlap". It is a promise, not a check. If you keep it, the compiler can generate faster code; if you break it, the behavior is undefined. This lesson goes deeper than the short introduction in Pointers and Functions: what exactly is promised, when the promise is safe, and how the standard library uses it.

The aliasing problem

Consider a function that copies one array into another, adding a fixed amount:

C
void add_offset(int *dst, const int *src, int n, int offset)
{
    for (int i = 0; i < n; i++) {
        dst[i] = src[i] + offset;
    }
}

Without more information, the compiler must assume dst and src might overlap. If dst is src + 1, then writing dst[0] changes src[1], which the next iteration reads. So the compiler has to do each load and store in order, one element at a time, and it can't safely load src[4] early or process four elements together with SIMD instructions.

flowchart LR
    subgraph "May alias: unknown"
        A["dst"] -.->|"could be the same memory"| B["src"]
    end
    subgraph "restrict: promised separate"
        C["dst"] --- D["src"]
    end

Without restrict the compiler must assume the two arrays might overlap. With restrict it may treat them as independent.

What restrict promises

You declare it on a pointer: int *restrict dst. The promise, in plain words:

During the lifetime of this pointer (for a parameter: while the function runs), if the object it points to is modified by any means, then every access to that object goes through this pointer (or through pointers derived from it, such as dst + 1 or &dst[2]).

Two details make this practical:

  1. The promise is only about objects that are modified. Two restrict pointers may point at the same memory as long as nobody writes to it.
  2. It is about the objects accessed, not the pointer values: two restrict pointers into different parts of the same array are fine if their accessed ranges don't overlap.
C
void add_offset(int *restrict dst, const int *restrict src, int n, int offset);

Now the compiler may assume writes to dst[i] never change anything read through src. It can hoist loads, unroll, vectorize and reorder freely.

Note: restrict is a qualifier on the pointer, so it goes after the *, like const does in int *const p. restrict int *p is an error. The qualifier applies to pointer types only; you can't restrict an int.

Safe uses: read-only aliasing

Because the promise concerns modified objects, passing the same memory twice is allowed when the function only reads it:

C Aliased read-only restrict pointers are fine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Both calls are valid: the second passes the same array twice, but since dot never writes, no modified object is reachable through two different pointers.

Unsafe uses: write through one, read through another

The moment one of the pointers writes to memory the other can also reach, the promise is broken and the behavior is undefined:

C
int a[5] = {1, 2, 3, 4, 5};
add_offset(a + 1, a, 4, 10);   /* BROKEN: writes a[1..4] while reading a[0..3] */

The compiler does not complain (at most you get a -Wrestrict warning for obvious cases), and the result might even look right at -O0 and be wrong at -O2. Never test a restrict violation by running it and seeing "it worked". When two ranges can overlap, either drop restrict from the signature or handle the overlap yourself.

Checking the contract in debug builds

A function that is going to rely on restrict can verify, at least during development, that the caller kept the promise. Compare the address ranges after converting to uintptr_t (comparing unrelated pointers with < is itself not portable, but integers are safe to compare):

C Verifying a no-overlap contract

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The assert disappears when you compile with -DNDEBUG, so release builds pay nothing (see Predefined Macros and assert). In debug builds, a wrongly overlapping call stops with a clear message instead of silently producing garbage.

restrict in the standard library

The C library uses restrict on parameters to document which calls must not overlap:

Function Overlap allowed? Why
memcpy(dest, src, n) No (restrict) A forward byte-by-byte or word-by-word copy can be wrong when ranges overlap, so it is free to pick the fastest strategy
memmove(dest, src, n) Yes Handles overlap by choosing the copy direction
strcpy, strcat, strncpy No (restrict) Same reasoning
sprintf(buf, fmt, ...) buf must not overlap the arguments Passing buf as one of the %s arguments is undefined
printf(fmt, ...) Format is restrict The format string must not be modified during the call

This is why you must use memmove when shifting elements within one array:

C memmove handles overlap, memcpy does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

If you wrote memcpy instead of memmove in that program, it might still print the right answer on your machine, which is the worst outcome: the bug appears when the library's copy routine changes.

Other places restrict appears

  • Array parameters: void f(int a[restrict], size_t n) means the same as int *restrict a (declared in the brackets of a parameter, together with static and const).
  • Block-scope pointers: a local int *restrict p = ...; promises that, within the block, the data it points to is only reached through p.
  • C++: there is no standard restrict. GCC, Clang and MSVC offer __restrict as an extension, and it behaves similarly.
  • Struct members: allowed, but the rules are intricate and rarely worth it; stick to function parameters.

Should you use it?

Add restrict when all these are true:

  1. The function is a hot spot you have measured (numeric loops, buffer filters, image or audio processing).
  2. It takes two or more pointers and writes through at least one.
  3. You control or can document every caller, and the contract "these ranges don't overlap" is natural for the function.

Do not add it to every pointer parameter just in case. The potential gain is real for tight array loops, but the cost of a violation is invisible undefined behavior that only shows up under certain compilers or flags. Write the contract in a comment, consider an assert like the one above, and run your tests with sanitizers (see Debugging C Programs). Read the details of undefined behavior in Undefined Behavior, and see the keyword in the C reference.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does declaring a parameter int *restrict p promise to the compiler?

    restrict is a no-aliasing promise. It does not mean non-null or constant. It lets the compiler assume writes through other pointers don't change what p points to, and vice versa.
  2. 2. A function has two const int *restrict parameters and never writes to memory. Is calling f(a, a, n) with the same array valid?

    The restrict promise matters only for objects that are modified. Two read-only pointers to the same data are fine.
  3. 3. You need to remove an element from the middle of an array by shifting the rest left inside the same array. Which call is correct?

    memcpy has restrict parameters and is undefined for overlapping ranges. memmove is specified to work as if it copied through a temporary buffer.
  4. 4. What happens if you call a function with restrict parameters and pass overlapping, written-to memory?

    restrict is a promise, not a check. Breaking it is undefined behavior, which often works at -O0 and fails only after optimization.
  5. 5. Where does the qualifier go in a pointer declaration?

    Like const in int *const p, restrict qualifies the pointer itself, so it follows the asterisk.

Summary

  • Two pointers alias when they can reach overlapping memory; the compiler must assume they might, which blocks optimizations.
  • restrict (C99) promises that memory modified during the pointer's lifetime is accessed only through that pointer (or pointers derived from it).
  • The promise is about modified objects: aliasing is fine when nothing is written.
  • Violating it is undefined behavior and is not diagnosed in general; verify the contract with comments, assert and sanitizers.
  • The library uses it to mark non-overlapping functions (memcpy, strcpy); use memmove when ranges may overlap.
  • Use restrict sparingly, on measured hot paths with a clear no-overlap contract.

Next: Dynamic Memory Allocation