Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
Do not cast away a {{const}} qualification on a variable type. Casting away the {{const}} qualification willallows allow violation of rule \[[EXP31-C. Do not modify constant values]\] prohibiting the modification of constant values.

...

The remove_spaces() function in this non-compliant code 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 as an argument.  The const qualification away and proceeds to modify the contentsis cast away; after which the contents of the string are modified.

Code Block
bgColor#FFcccc
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';
}

...

In this compliant solution the function remove_spaces() is passed a non-const char pointer. The calling function must ensure that the NULLnull-terminated byte string passed to the function is not const by making a copy of the string or by other means.

...

Non-Compliant Code Example

In this non-compliant code example, a the contents of }}the {{const int array vals is declared and its content modified by are cleared by the call to memset() with the function, clearing the contents of the vals array.

Code Block
bgColor#FFcccc
const int vals[] = {3, 4, 5};
memset(vals, 0, sizeof(vals));

...