|
| 1 | +<!DOCTYPE qhelp PUBLIC |
| 2 | + "-//Semmle//qhelp//EN" |
| 3 | + "qhelp.dtd"> |
| 4 | +<qhelp> |
| 5 | + |
| 6 | + |
| 7 | +<overview> |
| 8 | +<p> |
| 9 | +This query finds calls of <tt>scanf</tt>-like functions with missing or |
| 10 | +improper return-value checking. |
| 11 | +</p> |
| 12 | +<p> |
| 13 | +Specifically, the query flags uses of variables that may have been modified by |
| 14 | +<tt>scanf</tt> and subsequently are used without being guarded by a correct |
| 15 | +return-value check. A proper check is one that asserts the corresponding |
| 16 | +<tt>scanf</tt> to have returned (at least) a certain minimum constant. |
| 17 | +</p> |
| 18 | +<p> |
| 19 | +Functions in the <tt>scanf</tt> family return either EOF (a negative value) |
| 20 | +in case of IO failure, or the number of items successfully read from the |
| 21 | +input. Consequently, a simple check that the return value is truthy (nonzero) |
| 22 | +is not enough. |
| 23 | +</p> |
| 24 | +<warning> |
| 25 | +This query has medium precision because, in the current implementation, it |
| 26 | +takes a strict stance on unguarded uses of output variables, and flags them |
| 27 | +as problematic even if they had already been initialized. |
| 28 | +</warning> |
| 29 | +</overview> |
| 30 | + |
| 31 | +<recommendation> |
| 32 | +<p> |
| 33 | +Ensure that all subsequent uses of <tt>scanf</tt> output arguments occur in a |
| 34 | +branch of an <tt>if</tt> statement (or similar), in which it is known that the |
| 35 | +corresponding <tt>scanf</tt> call has in fact read all possible items from its |
| 36 | +input. This can be done by comparing the return value to a numerical constant. |
| 37 | +</p> |
| 38 | +</recommendation> |
| 39 | + |
| 40 | +<example> |
| 41 | +<p>This example shows different ways of guarding a <tt>scanf</tt> output: |
| 42 | +</p> |
| 43 | +<sample src="MissingCheckScanf.cpp" /> |
| 44 | +</example> |
| 45 | + |
| 46 | +<references> |
| 47 | +<li>SEI CERT C++ Coding Standard: <a href="https://wiki.sei.cmu.edu/confluence/display/cplusplus/ERR62-CPP.+Detect+errors+when+converting+a+string+to+a+number">ERR62-CPP. Detect errors when converting a string to a number</a>.</li> |
| 48 | +<li>SEI CERT C Coding Standard: <a href="https://wiki.sei.cmu.edu/confluence/display/c/ERR33-C.+Detect+and+handle+standard+library+errors">ERR33-C. Detect and handle standard library errors</a>.</li> |
| 49 | +<li>cppreference.com: <a href="https://en.cppreference.com/w/c/io/fscanf">scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s</a></li> |
| 50 | +</references> |
| 51 | +</qhelp> |
0 commit comments