...
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 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)
...
Code Block |
---|
|
char *tmpvar;
char *tempvar;
size_t len;
errno_t err = _dupenv_s(&tmpvar, &len, "TMP");
if (err) return -1;
errno_t err = _dupenv_s(&tempvar, &len, "TEMP");
if (err) {
free(tmpvar);
tmpvar = NULL;
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");
}
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;
|
Compliant Solution (POSIX)
...
Code Block |
---|
|
char *tmpvar;
char *tempvar;
char *temp;
if ((temp = strdup(getenv("TMP"));
char *tempvar = strdup( != NULL) {
tmpvar = strdup(temp);
if (tmpvar == NULL) {
/* handle error condition */
}
}
else {
return -1;
}
if ((temp = getenv("TEMP")) != NULL) {
tempvar = strdup(temp);
if (tempvar == NULL) {
free(!tmpvar) return -1;
if (!tempvar) ;
tmpvar = NULL;
/* handle error condition */
}
}
else {
free(tmpvar);
tmpvar = NULL;
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");
}
|
...
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;
|
Compliant Solution
This compliant solution is fully portable.
Code Block |
---|
|
char *tmpvar;
char *tempvar;
char *temp;
if ( (temp = getenv("TMP")) != NULL) {
tmpvar = (char *)malloc(strlen(temp)+1);
if (tmpvar != NULL) {
strcpy(tmpvar, temp);
}
else {
/* handle error condition */
}
}
else {
return -1;
}
if ( (temp = getenv("TEMP")) != NULL) {
tempvar = (char *)malloc(strlen(temp)+1);
if (tempvar != NULL) {
strcpy(tempvar, temp);
}
else {
free(tmpvar);
tmpvar = NULL;
/* handle error condition */
}
}
else {
free(tmpvar);
tmpvar = NULL;
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");
}
free(tmpvar);
tmpvar = NULL;
free(tempvar);
tempvar = NULL;
|
Risk Assessment
Storing the pointer to the string returned by getenv()
can result in overwritten environmental data.
...