...
| Code Block | ||
|---|---|---|
| ||
void remove_spaces(char const char *str, size_t slen) { char *p = (char*)str; size_t i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } *p = '\0'; } |
/
Compliant Solution
In this compliant solution the function remove_spaces() 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.
...
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.
| Code Block | ||
|---|---|---|
| ||
int const int vals[] = {3, 4, 5}; memset(vals, 0, sizeof(vals)); |
...
An exception to this rule is allowed when it is necessary to cast away const when invoking a legacy API that does not accept a const argument, provided the function does not attempt to modify the referenced variable. For example, the following code casts away the const qualification of INVFNAME in the call to the log() function.
| Code Block |
|---|
void log(char *errstr) {
fprintf(stderr, "Error: %s.\n", errstr);
}
/* ... */
const char INVFNAME[] = "Invalid file name.";
log((char *)INVFNAME);
/* ... */
|
Risk Assessment
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.
...