You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

Title Change?

Perhaps this might be more appropriate: ENV31-C. Use environ instead of envp.

Under many UNIX systems it is possible to access the environment through a modified form of main:

main(int argc, char **argv, char **envp) \{\}

According to C99,

In a hosted environment, the main function receives a third argument, char *envp[], that points to a null-terminated array of pointers to char, each of which points to a string that provides information about the environment for this execution of the program.

However, any environment variables added using the setenv() or putenv() functions will not show up in the envp array. If you need to directly access or manipulate the environment, it is safer to use environ.

Non-Compliant Coding Example

After a call to setenv(), environment pointers to the old value and copies of the old value may be incorrect.

char *temp;
char *copy;

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

/* ...program code... */
setenv("TEST_ENV", var, 1);
/* ...program code... */


printf("TEST_ENV: %s\n", temp);
printf("TEST_ENV: %s\n", copy);

Neither of the print statements will be correct.

Compliant Solution

You should always fetch fresh copies of environment variables, especially if you know that a value has changed.

char *temp;
char *copy;

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

/* ...program code... */
setenv("TEST_ENV", var, 1);
/* ...program code... */

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

printf("TEST_ENV: %s\n", temp);
printf("TEST_ENV: %s\n", copy);

This will provide us with the current value of the environment variable.

Risk Assessment

The program would not be using current environment values, causing unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ENV31-C

1 (low)

1 (low)

3 (low)

P3

L3

References

[[ISO/IEC 9899-1999:TC2]] Section 7.20.4, "Communication with the environment"

  • No labels