Versions Compared

Key

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

...

Compliant Solution (POSIX)

Wiki Markup
The following compliant solution depends on the POSIX {{strdup()}} function to make a copy of the environment variable string.  The {{strdup()}} function is also included in ISO/IEC PDTR 24731-2 \[[ISO/IEC PDTR 24731-2|AA. C References#ISO/IEC ISO/IEC PDTR 24731-2]\].

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

char *temp;

if ((temp = getenv("TMP"));
if (temp != NULL) {
  tmpvar = strdup(temp);
  if (tmpvar == NULL) {
    /* handle error condition */
  }
}
else {
  return -1;
}

if ((temp = getenv("TEMP"));
if (temp != NULL) {
  tempvar = strdup(temp);
  if (tempvar == NULL) {
    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;

...

Compliant Solution

This compliant solution is fully portable.

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

char *temp;

if ((temp = getenv("TMP"));
if (temp != NULL) {
  tmpvar = (char *)malloc(strlen(temp)+1);
  if (tmpvar != NULL) {
    strcpy(tmpvar, temp);
  }
  else {
    /* handle error condition */
  }
}
else {
  return -1;
}

if ((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 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;

...