...
This noncompliant code example compares the value of the TMP and TEMP environment variables to determine if they are the same.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *tmpvar;
char *tempvar;
tmpvar = getenv("TMP");
if (!tmpvar) return -1;
tempvar = getenv("TEMP");
if (!tempvar) return -1;
if (strcmp(tmpvar, tempvar) == 0) {
if (puts("TMP and TEMP are the same.\n") == EOF) {
/* Handle error */
}
}
else {
if (puts("TMP and TEMP are NOT the same.\n") == EOF) {
/* Handle error */
}
}
|
...
Windows provides the getenv_s() and _wgetenv_s() functions for getting a value from the current environment [MSDN].:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *tmpvar;
char *tempvar;
size_t requiredSize;
getenv_s(&requiredSize, NULL, 0, "TMP");
tmpvar = (char *)malloc(requiredSize * sizeof(char));
if (!tmpvar) {
/* Handle error */
}
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 */
}
getenv_s(&requiredSize, tempvar, requiredSize, "TEMP" );
if (strcmp(tmpvar, tempvar) == 0) {
if (puts("TMP and TEMP are the same.\n") == EOF) {
/* Handle error */
}
}
else {
if (puts("TMP and TEMP are NOT the same.\n") == EOF) {
/* Handle Error */
}
}
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;
|
...
This compliant solution uses only the C malloc() and strcpy() functions to copy the string returned by getenv() into a dynamically allocated buffer.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *tmpvar;
char *tempvar;
const char *temp = getenv("TMP");
if (temp != NULL) {
tmpvar = (char *)malloc(strlen(temp)+1);
if (tmpvar != NULL) {
strcpy(tmpvar, temp);
}
else {
/* Handle error */
}
}
else {
return -1;
}
temp = getenv("TEMP");
if (temp != NULL) {
tempvar = (char *)malloc(strlen(temp)+1);
if (tempvar != NULL) {
strcpy(tempvar, temp);
}
else {
free(tmpvar);
tmpvar = NULL;
/* Handle error */
}
}
else {
free(tmpvar);
tmpvar = NULL;
return -1;
}
if (strcmp(tmpvar, tempvar) == 0) {
if (puts("TMP and TEMP are the same.\n") == EOF) {
/* Handle error */
}
}
else {
if (puts("TMP and TEMP are NOT the same.\n") == EOF) {
/* Handle error */
}
}
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;
|
...
| [ISO/IEC 9899:2011] | Section 7.22.4, "Communication with the Environment" Section 7.22.4.6, "The getenv Function" |
| [MSDN] | _dupenv_s() and _wdupenv_s()getenv_s(), _wgetenv_s() |
| [Open Group 2004] | Chapter 8, "Environment Variables"strdup |
| [Viega 2003] | Section 3.6, "Using Environment Variables Securely" |
...