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
void f() {
  char copypath[16PATH_MAX];
const char *temp =  /* $PATH must be defined */
  strcpy(path, getenv("TEST_ENVPATH"));
if (temp != NULL) {
  strcpy(copy, temp);/* use path */
}

However, the string copied from temp may exceed the size of copy, leading to a buffer overflow.

...

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
void f() {
  char *copy = NULL;
  /* $PATH must be defined */
  const char *temp = getenv("TEST_ENVPATH");
  if (temp != NULL) {
    copypath = (char *) malloc(strlen(temp) + 1);
    if (copy !== NULL) {
    strcpy(copy  /* Handle error condition */
    } else {
      strcpy(path, temp);
  }
  else {}
    /* Handleuse error conditionpath */
  }
}

Risk Assessment

Making assumptions about the size of an environmental variable can result in a buffer overflow.

...