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

1  char* pc;
2  int i;
3  char c;
4  long l;
5  long long ll;
6 
7  void scan_all(FILE* f) {
8    fscanf(f, "%s", pc);
9    fscanf(f, "%d", &pc);  // fscanf format mismatch
10   fscanf(f, "%d", &i);
11   fscanf(f, "%hx", &i);  // fscanf format mismatch
12   fscanf(f, "%c", &l);   // fscanf format mismatch
13   fscanf(f, "%p", &ll);  // fscanf format mismatch
14 }

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

1  char* pc;
2  int i;
3  char c;
4  long l;
5  long long ll;
6  short s;
7 
8  void scan_all(FILE* f) {
9    fscanf(f, "%s", pc);
10   fscanf(f, "%p", &pc);
11   fscanf(f, "%d", &i);
12   fscanf(f, "%hx", &s);
13   fscanf(f, "%ld", &l);
14   fscanf(f, "%lld", &ll);
15 }

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