Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CPP: Add query for detecteing incorrect error checking for scanf #14910

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

alexet
Copy link
Contributor

@alexet alexet commented Nov 24, 2023

No description provided.

Copy link
Contributor

QHelp previews:

cpp/ql/src/Critical/IncorrectCheckScanf.qhelp

Incorrect return-value check for a 'scanf'-like function

This query finds calls of scanf-like functions with improper return-value checking.

Specifically, the query flags uses of scanf wehere the reurn value is checked only 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.

Recommendation

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

Example

This example shows different ways of guarding a scanf output:

{
  int i, j;

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

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

  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) {
    return;
  }
  if (r == 1) { 
    j = 0;
  }
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant