Section 7.21.7.10 of C11 the C Standard [ISO/IEC 9899:2011] defines ungetc() as follows:
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp; char *file_name; /* initializeInitialize file_name */ fp = fopen(file_name, "rb"); if (fp == NULL) { /* Handle error */ } /* readRead data */ if (ungetc('\n', fp) == EOF) { /* Handle error */ } if (ungetc('\r', fp) == EOF) { /* Handle error */ } /* continueContinue 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 applies only applies if the input is seekable.
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp; fpos_t pos; char *file_name; /* initializeInitialize file_name */ fp = fopen(file_name, "rb"); if (fp == NULL) { /* Handle error */ } /* readRead data */ if (fgetpos(fp, &pos)) { /* Handle error */ } /* readRead the data that will be "pushed back" */ if (fsetpos(fp, &pos)) { /* Handle error */ } /* Continue on */ |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Bibliography
...
| ] | Section 7.21.7. |
...
10, "The ungetc |
...
| Function" |
...