SV.FMT_STR.SCAN_FORMAT_MISMATCH.BAD

Mismatched specification and parameter

Scan function parameters can be pointers to items of various types, and therefore those items can occupy different amounts of memory. If a scan function parameter points to a memory item whose size is less than that expected from the corresponding format-string specification, a vulnerability can result. The SV.FMT_STR.SCAN_FORMAT_MISMATCH.BAD checker flags code in which the type size of the memory item pointed by the scan parameter and the corresponding format-string specification don't match.

Vulnerability and risk

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

Vulnerable code example

1   # include <string>
2   # include <stdio.h>
3
4   std::string scan_int() {
5     int length;
6     std::string str;
7     scanf("%lf", &length); // defect
8     scanf("%s\n", str);    // defect
9   }

Klocwork flags line 7 because the %lf specification doesn't match the parameter of type int. Amount of memory usually required for type double, which is expected for the %lf specification, is always greater than that required for type int, pointer to which is actually provided. A memory access violation may occur when trying to access memory required for double when memory required for int is actually allocated.

Line 8 is flagged because an object is actually provided for the %s specification, while a C string is expected. A memory access violation can be caused when an attempt is made to write bytes to the memory occupied by the object.

Fixed code example

1   # include <string>
2   # include <stdio.h>
3
4   std::string scan_int() {
5     int length;
6     char *str;
7     scanf("%d", &length); 
8     str = (char *)malloc(length + 1);
9     scanf("%s\n", str);   
10  }

In line 7 of the fixed code, the correct format specifier, %d, is used for printing an integer value. In line 9, a preliminary allocated C string is used instead of std::string.