CERT.STR.ASSIGN.CONST_TO_NONCONST

Do not assign a const char pointer to a non-const char pointer.

Vulnerability and risk

String literals are created at compile time to be of sufficient length and null terminated. The behavior is undefined if a program attempts to modify any portion of a string literal. Ideally, they should be assigned only to pointers to (or arrays of) const char or const whar_t.

This checker looks for assignments of string literals or const string pointers to non-const pointers.

This checker also treats the returned pointer as a const for calls to strpbrk(), strchr(), strrchr(), strstr(), wcspbrk(), wcschr(), wcsrchr(), wcsstr(), memchr(),wmemchr() when the first parameter is a const or string literal.

Mitigation and prevention

Use "const" on pointer declarations when the pointer shouldn't modify a string.

Example

Copy
  const char *get_dirname_v1(const char *pathname) {
    char *str = "string literal";
    str[0] = 'S';
    char *slash;
    slash = strrchr(pathname, '/');
    if (slash) {
      *slash = '\0'; /* Undefined behavior */
    }
    return pathname;
  }

Violations will be reported on lines 2 and 5.