Versions Compared

Key

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

...

Wiki Markup
Alternatively, input character data as a null-terminated byte string and covert to an integer value using {{strtol()}} or a related function \[[INT06-A. Use strtol() to convert a string token to an integer]\].

...

Non-Compliant Code Example

This non-compliant code example uses the scanf() function to read a string from stdin and convert it to a long. The scanf() and fscanf() functions have undefined behavior if the value of the result of this operation cannot be represented as an integer.

Code Block
bgColor#FFcccc

long sl;

scanf("%ld", &sl);

Compliant Solution

This compliant example uses fgets() to input a string and strtol() to convert the string to a an integer. Error checking is provided to make sure that the value is a valid integer in the range of long.

Code Block
bgColor#ccccff

char buff [25];
char *end_ptr;
long sl;

fgets(buff, sizeof buff, stdin);

errno = 0;

sl = strtol(buff, &end_ptr, 10);

if (ERANGE == errno) {
  puts("number out of range\n");
}
else if (end_ptr == buff) {
  puts("not valid numeric input\n");
}
else if ('\0' != *end_ptr) {
  puts("extra characters on input line\n");
}

Note that this solution treats any trailing characters, including white space characters, as an error condition.

...

Risk Assessment

While it is relatively rare for a violation of this rule to result in a security vulnerability, it could more easily result in loss or misinterpreted data.

...