Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: let there be const

...

This non-compliant code example compares the value of the TMP and TEMP environment variables to determine if they are the same. This code example is non-compliant because the string referenced by tmpvar may be overwritten as a result of the second call to the getenv() function. As a result, it is possible that both tmpvar and tempvar will compare equal even if the two environment variables have different values.

Code Block
bgColor#FFcccc
const char *tmpvar;
char, *tempvar;

tmpvar = getenv("TMP");
if (!tmpvar) return -1;
tempvar = getenv("TEMP");
if (!tempvar) return -1;

if (strcmp(tmpvar, tempvar) == 0) {
  puts("TMP and TEMP are the same.\n");
}
else {
  puts("TMP and TEMP are NOT the same.\n");
}

...

Microsoft Visual Studio 2005 provides provides the getenv_s() and _wgetenv_s() functions for getting a value from the current environment.

Code Block
bgColor#ccccff
char *tmpvar;
char *tempvar;
size_t requiredSize;

getenv_s(&requiredSize, NULL, 0, "TMP");
tmpvar= (char *)malloc(requiredSize * sizeof(char));
if (!tmpvar) {
   /* handle error condition */
}
getenv_s(&requiredSize, tmpvar, requiredSize, "TMP" );

getenv_s(&requiredSize, NULL, 0, "TEMP");
tempvar= (char *)malloc(requiredSize * sizeof(char));
if (!tempvar) {
   free(tmpvar);
   tmpvar = NULL;
   /* handle error condition */
}
getenv_s(&requiredSize, tempvar, requiredSize, "TEMP" );

if (strcmp(tmpvar, tempvar) == 0) {
  puts("TMP and TEMP are the same.\n");
}
else {
  puts("TMP and TEMP are NOT the same.\n");
}
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;:

Compliant Solution (Windows)

...