CodeQL documentation

Incorrect return-value check for a ‘scanf’-like function

ID: cpp/incorrectly-checked-scanf
Kind: problem
Security severity: 7.5
Severity: warning
Precision: high
   - security
   - correctness
   - external/cwe/cwe-253
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

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.

  int i, j;

  // BAD: The result is only checked against zero
  if (scanf("%d %d", &i, &j)) { 

  // BAD: The result is only checked against zero
  if (scanf("%d %d", &i, &j) == 0) { 
    i = 0;
    j = 0;

  if (scanf("%d %d", &i, &j) == 2) { 
      // GOOD: the result is checked against 2

  // GOOD: the result is compared directly
  int r = scanf("%d %d", &i, &j);
  if (r < 2) {
  if (r == 1) { 
    j = 0;


  • © GitHub, Inc.
  • Terms
  • Privacy