Versions Compared

Key

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

...

This noncompliant code example copies the string returned by getenv() into a fixed-size buffer.

Code Block
bgColor#FFcccc
langc
void f() {
  char path[PATH_MAX]; /* requires PATH_MAX to be defined */
  strcpy(path, getenv("PATH"));
  /* use path */
}

...

In the following compliant solution, the strlen() function is used to calculate the size of the string, and the required space is dynamically allocated.

Code Block
bgColor#ccccff
langc
void f() {
  char *path = NULL;
  /* avoid assuming $PATH is defined or has limited length */
  const char *temp = getenv("PATH");
  if (temp != NULL) {
    path = (char*) malloc(strlen(temp) + 1);
    if (path == NULL) {
      /* Handle error condition */
    } else {
      strcpy(path, temp);
    }
    /* use path */
  }
}

...