SV.FMT_STR.SCAN_FORMAT_MISMATCH.UNDESIRED

Unexpected specification and parameter match

The SV.FMT_STR.SCAN_FORMAT_MISMATCH.UNDESIRED checker flags code in which a scan function parameter and the corresponding format-string specification don't match. This checker reports a defect if the type size of the item pointed by the parameter is not less than that expected from the corresponding format-string specification.

Vulnerability and risk

Because the size of the type pointed by the parameter is greater than the size expected from the specification or even equal to it, there isn't a chance of memory corruption, but this situation may cause an unexpected value written to the pointed item. You can also face problems when porting this code to a different platform.

Vulnerable code example

Copy
  char* pc;
  int i;
  char c;
  long l;
  long long ll;
 
  void scan_all(FILE* f) {
    fscanf(f, "%s", pc);
    fscanf(f, "%d", &pc);  // fscanf format mismatch
   fscanf(f, "%d", &i);
   fscanf(f, "%hx", &i);  // fscanf format mismatch
   fscanf(f, "%c", &l);   // fscanf format mismatch
   fscanf(f, "%p", &ll);  // fscanf format mismatch
 }

Klocwork flags errors at lines 9, 11, 12 and 13 to indicate mismatches between the format-string specification and the parameter. The format specification shows that in line 9, a pointer to int is expected; In line 11, a pointer to short int is expected; In line 12, a pointer to char is expected and in line 13, a pointer to pointer is expected, and none of the parameters in these lines matches the expectation. However, because in all cases memory items occupied by the parameters are not smaller than those expected according to the specifications, the error is considered UNDESIRED rather than BAD. In contrast, lines 8, and 10 show matched examples of specification and parameter.

Fixed code example

Copy
  char* pc;
  int i;
  char c;
  long l;
  long long ll;
  short s;
 
  void scan_all(FILE* f) {
    fscanf(f, "%s", pc);
   fscanf(f, "%p", &pc);
   fscanf(f, "%d", &i);
   fscanf(f, "%hx", &s);
   fscanf(f, "%ld", &l);
   fscanf(f, "%lld", &ll);
 }

In the fixed examples, each format specification and parameter correspond.