Versions Compared

Key

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

The getenv() function searches an environment list for a string that matches a specified name, and returns a pointer to a string associated with the matched list member. Due to the way manner in which environment variables are stored, multiple environment variables with the same name can cause unexpected results. You may end up checking check one value, but actually returning return another.

Implementation Details

Depending on the implementation, a program may not consistently choose the same value if there are multiple environment variables with the same name. The GNU glibc library attempts to deal with addresses this issue in getenv() and setenv() by always using the first variable it comes across, and ignoring the rest. unsetenv() will remove all the entries matching the variable name. Other implementations are following this lead.The glibc getenv() and setenv() functions will always choose the same value, so using them is a good option.

Code Block
char *temp;
char *copy;

if ((temp = getenv("TEST_ENV")) != NULL) {
  copy= (char *)malloc(strlen(temp) + 1);
  if (copy != NULL) {
    strcpy(copy, temp);
  }
  else {
    /* handle error condition */
  }

  copy[0] = 'a';
  setenv("TEST_ENV", copy, 1);
}
else {
  return -1;
}

In addition, it is possible to search through environ checking for multiple entries of a variable. Upon finding a duplicate, abort()Any duplicate values are an indication of an attack; take appropriate action. It is very unlikely that there would be a need for more than one variable of the same name.

...