Versions Compared

Key

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

...

This noncompliant code example converts the string token stored in the static array buff to a signed integer value using the atoi() function.

Code Block
bgColor#FFcccc
langc
int si;

if (argc > 1) {
  si = atoi(argv[1]);
}

...

This noncompliant example uses the sscanf() function to convert a string token to an integer. The sscanf() function has the same limitations as atoi().

Code Block
bgColor#FFcccc
langc
int matches; 
int si;

if (argc > 1) {
  matches = sscanf(argv[1], "%d", &si);
  if (matches != 1) {
    /* Handle error */
  }
}

...

This compliant solution uses strtol() to convert a string token to an integer and ensures that the value is in the range of int.

Code Block
bgColor#ccccff
langc
int main(int argc, char *argv[]) {

  if (argc < 2)
    return EXIT_SUCCESS;

  const char* const str = argv[1];
  char *end;
  int si;

  errno = 0;

  const long sl = strtol(str, &end, 10);

  if (end == str) {
    fprintf(stderr, "%s: not a decimal number\n", str);
  }
  else if ('\0' != *end) {
    fprintf(stderr, "%s: extra characters at end of input: %s\n", str, end);
  }
  else if ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno) {
    fprintf(stderr, "%s out of range of type long\n", str);
  }
  else if (sl > INT_MAX) {
    fprintf(stderr, "%ld greater than INT_MAX\n", sl);
  }
  else if (sl < INT_MIN) {
     fprintf(stderr, "%ld less than INT_MIN\n", sl);
  }
  else {
    si = (int)sl;

    /* process si */

    return EXIT_SUCCESS;
  }
  return EXIT_FAILURE;
}

...