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

Copy
   # include <string>
   # include <stdio.h>

   std::string scan_int() {
     int length;
     std::string str;
     scanf("%lf", &length); // defect
     scanf("%s\n", str);    // defect
   }

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

Copy
   # include <string>
   # include <stdio.h>

   std::string scan_int() {
     int length;
     char *str;
     scanf("%d", &length); 
     str = (char *)malloc(length + 1);
     scanf("%s\n", str);   
  }

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.