When Do not attempt to modify a variable, array, or pointer is declared as const, do not attempt to modify it. The specification of const in variables and parameters implies to a maintainer or caller that, despite knowing some memory location, the code will not modify its content. Although C allows you to remove the specifier using typecasts, doing so violates the implication of the specifier.
Non-
...
Compliant Code Example
...
In the following example, the function f is passed a const char pointer. It then typecasts the const specification away, and proceeds to modify the contents.
| Code Block |
|---|
void f(const char *str, int slen) {
char *p = (char*)str;
int i;
for (i = 0; i < slen && str[i]; i++) {
if (str[i] != ' ') *p++ = str[i];
}
}
|
Compliant Solution
In the following compliant solution the function f is passed a non-const char pointer. The calling function must ensure that the null-terminated byte string passed to the function is not const by making a copy of the string or by other means.
| Code Block |
|---|
void f(char *str, int slen) { char *p = str; int i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } } |
Non-
...
Complaint Code Example
...
In this example, a const int array vals is declared , and then its content is modified by calling memset() with the function, leading to values of 0 in clearing the contents of the vals array.
| Code Block |
|---|
const int vals[] = {3, 4, 5};
memset((int *)vals, 0, sizeof(vals));
|
Complaint Code Example
If the intention is to allow the array values to be modified, do not declare the array as const.
| Code Block |
|---|
int vals[] = {3, 4, 5};
memset((int *)vals, 0, sizeof(vals));
|
Otherwise, do not attempt to modify the contents of the array.
Consequences
If the object really is constant, the compiler may have put it in ROM or write-protected memory. Trying to modify such an object may lead to a program crash. This could allow an attacker to mount a denial of service attack.
...