Checkers:SV.FMT_STR.SCAN_FORMAT_MISMATCH

From current

Reference > C/C++ checkers > SV.FMT STR.SCAN FORMAT MISMATCH

Mismatched scan specification and parameter

Scan function parameters can occupy stack memory blocks that consist of whole numbers of machine words. If a scan function parameter occupies an amount of stack memory different from that expected from the corresponding format-string specification, a vulnerability can result. The SV.FMT_STR.SCAN_FORMAT_MISMATCH checker flags code in which the size of the memory block for the scan parameter and the corresponding format-string specification don't match.

Vulnerability and risk

A mismatched parameter and format-string specification can cause memory access violation and may lead to undesired program execution results. Undefined behavior and abnormal program termination are possible.

Code examples

Vulnerable code example

1 void foo(FILE* f, char* pc, int i, char c, long long ll, struct SomeStruct ss) {
2     fscanf(f, "%s", &i);         // fscanf format mismatch: incompatible parameter type
3     fscanf(f, "%lld", &ll);
4     fscanf(f, "%hx", &i);
5     fscanf(f, "%c", &ll);        // fscanf format mismatch: incompatible parameter type
6     fscanf(f, "%ld", &ss);       // fscanf format mismatch: incompatible parameter type
7 }

Klocwork flags errors at lines 2, 5, and 6 to indicate mismatches between the format-string specification and the parameter. The format specification shows that in line 2, a character string is expected, in line 5, a character is expected, and in line 6, a long integer is expected, and none of the parameters in these lines matches the expectation. In contrast, lines 3 and 4 show matched examples of specification and parameter.

Fixed code example

1 void foo(FILE* f, char* pc, int i, char c, long long ll, struct SomeStruct ss) {
2     fscanf(f, "%s", pc);
3     fscanf(f, "%lld", &ll);
4     fscanf(f, "%hx", &i);
5     fscanf(f, "%c", c);       
6     fscanf(f, "%ld", l);
7 }

In the fixed code example, there are no mismatches between the format-string specification and the parameter.

Related checkers

External guidance