Versions Compared

Key

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

...

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

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

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

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

if (setenv("TEST_ENV", copy_of_env, 1) != 0) {
  /* Handle error */
}

Noncompliant Code Example

This noncompliant code example modifies the string returned by setlocale() by terminating the string when ‘.’ is encountered such as “en_US.iso88591” to “en_US”. In this case, the behavior is undefined.

Code Block
bgColor#ffcccc

void terminate_on_dot(char *str){
  int i;

  for (i = 0; i < strlen(locale); i++){
    if(locale[i] == ‘.’){
      locale[i] = ‘\0’;
      break;
    }
  }
}

/* ... */

char *locale = setlocale(LC_ALL, "");
if (locale == NULL) {
  /* Handle error */
}

terminate_on_dot(locale);

/* ... */

Compliant Solution

Similar to the case of getenv(), this compliant solution makes a local copy of that string value and then modifies the local copy.

Code Block
bgColor#ccccff

const char *locale;
char *copy_of_locale;

locale = setlocale(LC_ALL, "");
if (locale == NULL) {
  /* Handle error */
}

copy_of_locale = (char *)malloc(strlen(locale) + 1);
if (copy_of_locale == NULL) {
  /* Handle error */
}

strcpy(copy_of_locale, locale);
terminate_on_dot(copy_of_locale);

/* ... */

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.

...