Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider v2.4 (sch jbop) (X_X)@==(Q_Q)@

...

Likewise, for ungetwc() C99 only guarantees one wide character of pushback (section 7.24.3.10). Consequently, multiple calls to ungetwc() on the same stream must be separated by a call to a read function or a file-positioning function (which will discard any data pushed by ungetwc()).

...

Noncompliant Code Example

In this non-compliant noncompliant code example, more than one character is pushed back on the stream referenced by fp.

Code Block
bgColor#ffcccc
FILE *fp;
char *file_name;

/* initialize file_name */

fp = fopen(file_name, "rb");
if (fp == NULL) {
  /* handle Error */
}

/* read data */

if (ungetc('\n', fp) == EOF) {
  /* handle error */
}
if (ungetc('\r', fp) == EOF) {
  /* handle error */
}

/* continue on */

Compliant Solution

If more than one character needs to be pushed by ungetc(), then fgetpos() and fsetpos() should be used before and after reading the data instead of pushing it back with ungetc(). Note that this solution can only be used if the input is seekable.

...

Remember to always call fgetpos() before fsetpos() (see FIO44-C. Only use values for fsetpos() that are returned from fgetpos()).

Risk Assessment

If used improperly, ungetc() and ungetwc() can cause data to be truncated or lost.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FIO13-A C

medium

probable

high

P4

L3

Automated Detection

Compass/ROSE can detect simple violations of this recommendation. In particular, it warns when two calls to ungetc() on the same stream are not interspersed with a file positioning or file read function. It is unable to handle cases where ungetc() is called from inside a loop.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Reference

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.19.7.11, "The {{ungetc}} function"

...

FIO12-C. Prefer setvbuf() to setbuf()      09. Input Output (FIO)       FIO14-A. Understand the difference between text mode and binary mode with file streams Image Added