Versions Compared

Key

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

...

This noncompliant code example sets str to reference either dynamically allocated memory or a statically allocated string literal depending on the value of argc. In either case, str is passed as an argument to free(). If anything other than dynamically allocated memory is referenced by str, the call to free(str) is erroneous.

Code Block
bgColor#FFcccc
langc
enum { MAX_ALLOCATION = 1000 };

int main(int argc, const char *argv[]) {
  char *str = NULL;
  size_t len;

  if (argc == 2) {
    len = strlen(argv[1])+1;
    if (len > MAX_ALLOCATION) {
      /* Handle error */
    }
    str = (char *)malloc(len);
    if (str == NULL) {
      /* Handle allocation error */
    }
    strcpy(str, argv[1]);
  }
  else {
    str = "usage: $>a.exe [string]";
    printf("%s\n", str);
  }
  /* ... */
  free(str);
  return 0;
}

...

This compliant solution eliminates the possibility of str, referencing nondynamic memory when it is supplied to free().

Code Block
bgColor#ccccff
langc
enum { MAX_ALLOCATION = 1000 };

int main(int argc, const char *argv[]) {
  char *str = NULL;
  size_t len;

  if (argc == 2) {
    len = strlen(argv[1])+1;
    if (len > MAX_ALLOCATION) {
      /* Handle error */
    }
    str = (char *)malloc(len);
    if (str == NULL) {
      /* Handle allocation error */
    }
    strcpy(str, argv[1]);
  }
  else {
    printf("%s\n", "usage: $>a.exe [string]");
    return -1;
  }
  /* ... */
  free(str);
  return 0;
}

...