Versions Compared

Key

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

Wiki Markup
DoC99 not modify the value returned by the defines {{getenv()}} function. Create a copy and make your changes locally, so that they are not overwritten.  According to C99 as follows \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]:

The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program, but may be overwritten by a subsequent call to the getenv function. If the specified name cannot be found, a null pointer is returned.

Consequently, if the string returned by getenv() needs to be altered, a local copy should be created to ensure that the environment is not directly and unintentionally modified.

Non-Compliant Code Example

This non-compliant code example modifies the string returned by getenv() by replacing all " characters with underscores.

Code Block
bgColor#ffcccc

void strtr(char *str, char orig, char rep) {
  while (*str != '\0') {
    if (*str == orig) {
      *str = rep;
    }
    str++;
  }
}
Code Block
bgColor#ffcccc
char *env = getenv("TEST_ENV");
if (env[0] == 'a' NULL) {
  /* Handle Error */
}

strtr(env,'\"', '_');

Compliant Solution (local copy)

...

Code Block
bgColor#ccccFF
char const *env;
char *copy_of_env;

env = getenv("TEST_ENV");
if (env !== NULL) {
  /* Handle Error */
}

copy_of_env = (char *)malloc(strlen(env) + 1);

   if (copy_of_env !== NULL) {
  /* Handle   Error */
}

strcpy(copy_of_env, env);
   }
   else {
      /* Error handling */
   }

   strtr(copy_of_env[0] =,'\"', 'a_');
}

Compliant Solution (modifying the environment in POSIX)

For the case where the intent of the non-compliant code example is to modify the environment, this compliant solution will perform that action save the replace the variable in the environment by using the POSIX putenvsetenv() and strdup() function functions.

Code Block
bgColor#ccccFF
char const *env;
char *copy_of_env;

env = getenv("TEST_ENV");
if (env !== NULL) {
  /* Handle Error */
}

copy_of_env = (char *)malloc(sizeof("TEST_ENV=") + strlen(env));

   strdup(env);
if (copy_of_env !== NULL) {
  /* Handle   strcpyError */
}

strtr(copy_of_env,'\"', "TEST_ENV="'_');
      strcat(copy_of_env, env);
      copy_of_env[sizeof
if (setenv("TEST_ENV=") - 1] = 'a';
      if (putenv(", copy_of_env, 1) != 0) {
        /* handle error */
      }
   }
   else {
      /* Error handling */
   }Handle Error */
}

Risk Assessment

The modified string may be overwritten by a subsequent call to the getenv() function.  Depending on the implementation, modifying the string returned by getenv() may or may not modify the environment.

...