...
Unlike passed-by-value arguments and pointers, pointed-to values are a concern. A function may modify a value referenced by a pointer argument, leading to a side effect which persists even after the function exits. Modification of the pointed-to value is not diagnosed by the compliercompiler, which assumes this was the intended behavior.
Code Block | ||
---|---|---|
| ||
void foo(int *x) { if (x != NULL) { *x = 3; /* visible outside function */ } /* ... */ } |
Compliant Solution
In this code example, If the function parameter is const
-qualified. Any , any attempt to modify the pointed-to value is diagnosed by the compilerresults in a fatal diagnostic.
Code Block | ||
---|---|---|
| ||
void foo(const int * x) {
if (x != NULL) {
*x = 3; /* generates compiler error */
}
/* ... */
}
|
Consequently the compiler will refuse to compile this function, forcing the programmer to solve As a result, the const
violation must be resolved before the code can be compiled.
Compliant Solution
This compliant solution addresses the const violation by not modifying the constant argument.
...
In the final strcat_nc()
call, the compiler generates a warning about attempting to cast away const
on str4
. This is a valid warning.
Compliant Solution
This compliant solution uses the prototype for the strcat()
from C90. Although the restrict
type qualifier did not exist in C90, const
did. In general, function parameters should be declared in a manner consistent with the semantics of the function. In the case of strcat()
, the initial argument can be changed by the function while the second argument cannot.
...