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].

The returned value of the library functions strpbrk(), strchr(), strrchr(), wcspbrk(), wcschr(), and wcsrchr() and pointer to (or array of) const characters shall be treated as a string literal.

...

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
#include <string.h>
 
const char *get_dirname(const char *pathname) {
  char *slash;
  slash = strrchr(pathname, '/');
  if (slash) {
    *slash = '\0'; /* undefinedUndefined behavior */
  }
  return pathname;
}

int main() {
  puts(get_dirname(__FILE__));
  return 0;
}

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <string.h>
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

Compass/ROSE

  

Can detect simple violations of this rule

LDRA tool suite

Include Page
LDRA_V
LDRA_V

157 S

Partially implemented
PRQA QA-C
Include Page
PRQA_V
PRQA_V
0556Partially implemented

Splint

Include Page
Splint_V
Splint_V
 

 

...

Bibliography

Annex J, J2, "Undefined behavior" 
[ISO/IEC 9899:2011]Annex J, subclause J.2, "Undefined Behavior" 
[Plum 1991]Topic 1.26, "Strings—String Literals"
[Summit 1995]comp.lang.c FAQ list, Question 1.32[ISO/IEC 9899:2011]

 

...