Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Add a POSIX/C2x solution, and free path at the end

...

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 */
    free(path);
  }
}

Compliant Solution (POSIX or C2x)

In this compliant solution, the strdup() function is used to dynamically allocate a duplicate of the string:

Code Block
bgColor#ccccff
languagec
void f() {
  char *path = NULL;
  /* Avoid assuming $PATH is defined or has limited length */
  const char *temp = getenv("PATH");
  if (temp != NULL) {
    path = strdup(temp);
    if (path == NULL) {
      /* Handle error condition */
    }
    /* Use path */
    free(path);
  }
}

Risk Assessment

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

...