...
In this noncompliant code example, the values of objects referenced by ptr1
and ptr2
become unpredictable after the call to memcpy()
because their memory areas overlap:file scope declarations assert that if an object is accessed using one of a
, b
, or c
, and that object is modified anywhere in the program, then it is never accessed using either of the other two.
Code Block | ||||
---|---|---|---|---|
| ||||
int * restrict a; int * restrict b; extern int c[]; int main(void) { a = c[0] = 17; b = c[1] = 18; *a = *b; /* undefined behavior */ } |
Compliant Solution
In this One compliant solution , is to simply remove the restrict-qualificatiers are removedqualification from the affected pointers.
Code Block |
---|
int * a; int * b; extern int c[]; int main(void) { a = c[0] = 17; b = c[1] = 18; *a = *b; /* undefined behavior */ } |
...
Noncompliant Code Example
The function parameter declarad in In this noncompliant code example assert that, , the function f()
accepts three parameters. The function copies n integers from the int
arrray referenced by the restrict-qualified pointer p
to the int
array referenced by the restrict-qualified pointer q
. Because the object is modified during each execution of the function (for which n
is nonzero), if an object is accessed through one of the pointer parameters , then it is not cannot also be accessed through the other. Declaring these function parameters as restrict-qualified pointers allows aggressive optimization by the compiler but can also result in undefined behavior if these pointers refer to overlapping objects.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(intsize_t n, int * restrict p, int * restrict q) { while (n-- > 0) *p++ = *q++; } void g(void) { extern int d[100]; /* ... */ f(50, d + 1, d); //* undefined behavior */ } |
The function g()
declares an array d
consisting of 100 int
values and then invokes f()
to copy memory from one area of the array to another. This call has undefined behavior because each of d[1]
through d[49]
is accessed through both p
and q
.
Compliant Solution
In this compliant solution, the function f()
is unchanged but the programmer has ensured that none of the calls to f()
result in undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(int n, int * restrict p, int * restrict q) { while (n-- > 0) *p++ = *q++; } void g(void) { extern int d[100]; f(50, d + 50, d); // valid } |
...