1

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?

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

5

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.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • hello interjay, so it is undefined behavior when you access the object through the alias pointer or if the pointer aliases the object? Your statement sounds like it matters only if the pointer pointing to the object is dereferences and that it doesn't matter if another pointer aliases so long as it's not dereferenced? – Nergal Jul 29 '18 at 19:00
  • ahhh so If I had another pointer alias the restricted pointer just to save the address and then restore it back to the restricted pointer, that's not undefined behavior? the reason for the question is because I'm working on a stack VM and the instruction pointer is restricted but the opcode needs to save the instruction pointer value to stack. I was worried this would've caused UB. – Nergal Jul 30 '18 at 18:06