Versions Compared

Key

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

...

At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a null-termination character. It is unspecified whether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation because string literals are typically stored in read-only memory. See also undefined behavior 33  of Annex J of the C standard [ISO/IEC 9899:2011].

...

In this noncompliant code example, the char pointer p is initialized to the address of a string literal. Attempting to modify the string literal results in undefined behavior.

Code Block
bgColor#FFcccc
langc
char *p  = "string literal";
p[0] = 'S';

...

A compliant solution avoids modifying a const object, even if it is possible to obtain a non-const pointer to such an object by calling a standard C library function, such as strrchr(). To reduce the risk of callers of get_dirname() passing constant objects to the function, the argument is declared to be a non-const pointer. Although converting a string literal to non-const char* is permitted by the language, conforming compilers could issue a diagnostic for such code. See also EXP05-C. Do not cast away a const qualification.

Code Block
bgColor#ccccff
langc
char* get_dirname(char* pathname) {
  char* slash;
  slash = strrchr(pathname, '/');
  if (slash)
    *slash = '\0';
  return pathname;
}

int main() {
  char pathname[] = __FILE__;
  /* calling get_dirname(__FILE__) may be diagnosed */
  puts(get_dirname(pathname));
  return 0;
}

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

157 S

Partially implemented.

Splint

Include Page
Splint_V
Splint_V
 

 

Compass/ROSE

  

Can detect simple violations of this rule.

PRQA QA-C
Include Page
PRQA_V
PRQA_V
 0556Partially implemented

Related Vulnerabilities

...

ISO/IEC TR 17961 (Draft) Modifying string literals [strmod]

Bibliography

[Summit 1995] comp.lang.c FAQ list, Question 1.32
[Plum 1991] Topic 1.26, "strings—string literals"

...