Versions Compared

Key

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

...

The remove_spaces() function in this noncompliant 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 toward the front of the string. The function remove_spaces() is passed a const char pointer as an argument. The const qualification is cast away and then the contents of the string are modified.

Code Block
bgColor#FFcccc
langc
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 null-terminated byte string passed to the function is not const by making a copy of the string or by other means.

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

...

In this noncompliant code example, the contents of the const int array vals are cleared by the call to memset().

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

...

If the intention is to allow the array values to be modified, do not declare the array as const.

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

...