Do not cast away a const qualification on a variable type. Casting away the const qualification will allow violation of rule \[[EXP31-C|EXP31-C. Do not modify constant values ]\] prohibiting the modification of constant values. |
In this example, the function f
is passed a const
char
pointer. It then typecasts the const
specification away, and proceeds to modify the contents.
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]; } } |
In this 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.
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]; } } |
In this example, a const
int
array vals
is declared and its content modified by memset()
with the function, clearing the contents of the vals
array.
const int vals[] = {3, 4, 5}; memset((int *)vals, 0, sizeof(vals)); |
If the intention is to allow the array values to be modified, do not declare the array as const
.
int vals[] = {3, 4, 5}; memset((int *)vals, 0, sizeof(vals)); |
Otherwise, do not attempt to modify the contents of the array.
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.
Component |
Value |
---|---|
Severity |
1 (low) |
Likelihood |
3 (likely) |
Remediation cost |
2 (low) |