Search code examples
cundefined-behaviorrestrict

Confusion about undefined behaviour for restrict qualifier


I saw the following example on cppreference.

void f(int n, int * restrict p, int * restrict q)
{
    while(n-- > 0)
        *p++ = *q++; // none of the objects modified through *p is the same
                     // as any of the objects read through *q
                     // compiler free to optimize, vectorize, page map, etc.
}
void g(void)
{
    extern int d[100];
    f(50, d + 50, d); // OK
    f(50, d + 1, d); // Undefined behavior: d[1] is accessed through both p and q in f
}

In that example,calling f(50, d + 50, d); is Ok.

But, i don't understand, calling f(50, d + 1, d); is undefined behaviour. Why?


Solution

  • The restrict qualifier on a pointer means that any object accessed through that pointer which is modified will not be accessed through other pointers during that pointer's lifetime. In other words, when an object is accessed through pointer p and modified during p's scope, then it can only be accessed through p in that scope. Violating this constraint leads to undefined behavior.

    In f(50, d + 50, d);, p will be used to modify d[50] up to d[99], and q will be used to access d[0] up to d[49]. There is no overlap so everything is fine.

    In f(50, d + 1, d);, p will be used to modify d[1] up to d[50], and q will be used to access d[0] up to d[49]. Since some elements (for example, d[1]) are modified through p and read through q, this is a violation of the restrict qualifier.