You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 24 Next »

Do not cast away a const qualification on a variable type. Casting away the const qualification will allow violation of rule [[EXP31-C]] prohibiting the modification of constant values.

Non-Compliant Code Example

The remove_spaces() function in this example accepts a pointer to a string str and a string length slen and removes the space character from the string by shifting the remaining characters towards the front of the string. The function remove_spaces() is passed a const char pointer. It then typecasts the const qualification away, and proceeds to modify the contents.

void remove_spaces(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.

void remove_spaces(char *str, size_t slen) {
   char *p = str;
   size_t i;
   for (i = 0; i < slen && str[i]; i++) {
      if (str[i] != ' ') *p++ = str[i];
   }
   *p = '\0';
}

Non-Compliant Code Example

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(vals, 0, sizeof(vals));

Compliant Solution

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(vals, 0, sizeof(vals));

Otherwise, do not attempt to modify the contents of the array.

Exception

It is acceptable 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.

void log(char *errstr) {
  fprintf(stderr, "Error: %s.\n", errstr);
}

...
const char INVFNAME[]  = "Invalid file name.";
log((char *)INVFNAME);
...

Priority: P4 Level: L3

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

2 (probable)

Remediation cost

2 (medium)

References

  • No labels