Versions Compared

Key

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

...

Code Block
bgColor#ccccff
langc
char a[] = "string literal";
a[0] = 'S';

Noncompliant Code Example (POSIX)

In this noncompliant code example, a string literal is passed to the (pointer to non-const) parameter of the POSIX function mkstemp(), which then modifies the characters of the string literal:

Code Block
bgColor#FFcccc
langc
#include <stdlib.h>
 
void func(void) {
  char *fname;
  fname = mkstemp("/tmp/edXXXXXX");

}

Compliant Solution (POSIX)

Instead of passing a string literal, use a named array:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
void func(void) {
  static char fname[] = "/tmp/edXXXXXX";
  mkstemp(fname);

}

Noncompliant Code Example (Result of strrchr())

...

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'; /* undefined 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__;
  /* callingCalling get_dirname(__FILE__) may be diagnosed. */
  puts(get_dirname(pathname));
  return 0;
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

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

 

...