关于限制限定符的未定义行为的混淆

msc*_*msc 1 c restrict undefined-behavior

我在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
}
Run Code Online (Sandbox Code Playgroud)

在那个例子中,呼叫f(50, d + 50, d);是好的.

但是,我不明白,打电话f(50, d + 1, d); 是未定义的行为.为什么?

int*_*jay 5

restrict指针上的限定符意味着通过该指针访问的任何对象在该指针的生命周期内都不会通过其他指针访问.换句话说,当通过指针访问对象p并在p范围内进行修改时,只能通过p该范围访问它.违反此约束会导致未定义的行为.

f(50, d + 50, d);,p将用于修改d[50]最多d[99],并将q用于访问d[0]最多d[49].没有重叠所以一切都很好.

f(50, d + 1, d);,p将用于修改d[1]最多d[50],并将q用于访问d[0]最多d[49].由于某些元素(例如d[1])被修改p并通读q,因此违反了restrict限定符.