This query finds calls of scanf-like functions with improper return-value checking. Specifically, it flags uses of scanf where the return value is only checked against zero.

Functions in the scanf family return either EOF (a negative value) in case of IO failure, or the number of items successfully read from the input. Consequently, a simple check that the return value is nonzero is not enough.

Ensure that all uses of scanf check the return value against the expected number of arguments rather than just against zero.

The following examples show different ways of guarding a scanf output. In the BAD examples, the results are only checked against zero. In the GOOD examples, the results are checked against the expected number of matches instead.

  • SEI CERT C++ Coding Standard: ERR62-CPP. Detect errors when converting a string to a number.
  • SEI CERT C Coding Standard: ERR33-C. Detect and handle standard library errors.
  • cppreference.com: scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s.