Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added reference to linux programmer's manual for Linux solution

...

Compliant Solution (Linux)

Wiki Markup
This compliant example uses the Linux {{scanf()}} implementation's built in error handling to validate input. On Linux platforms, {{scanf()}} sets {{errno}} to {{ERANGE}} if the result of integer conversion cannot be represented within the size specified by the format string \[[Linux Programmer's Manual|AA. C References#Linux 07]\]. Note that this is a platform dependent solution. Therefore, this should only be used where portability is not a concern.

Code Block
bgColor#ccccff
long sl;
errno = 0;

if (scanf("%ld", &sl) != 1) {
  /* handle error */
}
else if (ERANGE == errno) {
  if (puts("number out of range\n") == EOF) {
      /* Handle error */
  }
}

...

Wiki Markup
\[[Klein 02|AA. C References#Klein 02]\]
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.1.4, "The strtol, strtoll, strtoul, and strtoull functions," and Section 7.19.6, "Formatted input/output functions"
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 192|http://cwe.mitre.org/data/definitions/192.html], "Integer Coercion Error"; and [CWE ID 197|http://cwe.mitre.org/data/definitions/197.html], "Numeric Truncation Error"
\[[Linux Programmer's Manual|AA. C References#Linux 07]\]

...

INT04-C. Enforce limits on integer values originating from untrusted sources      04. Integers (INT)      INT06-C. Use strtol() or a related function to convert a string token to an integer