 
                            ...
| Code Block | ||
|---|---|---|
| 
 | ||
| 
int si;
if (argc > 1) {
  sscanf(argv[1], "%d", &si);
}
 | 
...
Compliant Solution
This compliant example uses strtol() to convert a string token to an integer value and provides error checking to make sure that the value is in the range of int.
| Code Block | ||
|---|---|---|
| 
 | ||
| 
long sl;
int si;
char *end_ptr;
if (argc > 1) {
  errno = 0;
  sl = strtol(argv[1], &end_ptr, 10);
  if (ERANGE == errno) {
    puts("number out of range\n");
  }
  else if (sl > INT_MAX) {
    printf("%ld too large!\n", sl);
  }
  else if (sl < INT_MIN) {
    printf("%ld too small!\n", sl);
  }
  else if (end_ptr == argv[1]) {
    puts("invalid numeric input\n");
  }
  else if ('\0' != *end_ptr) {
    puts("extra characters on input line\n");
  }
  else {
    si = (int)sl;
  }
}
 | 
If you are attempting to convert a string token to a smaller integer type (int, short, or signed char), then you only need test the result against the limits for that type. The tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.
...
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.
...