01.07.2016 Views

SEI CERT C Coding Standard

tqcylJ

tqcylJ

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Input/Output (FIO) - FIO38-C. Do not copy a FILE object<br />

10.5 FIO38-C. Do not copy a FILE object<br />

According to the C <strong>Standard</strong>, 7.21.3, paragraph 6 [ISO/IEC 9899:2011],<br />

The address of the FILE object used to control a stream may be significant; a copy of a<br />

FILE object need not serve in place of the original.<br />

Consequently, do not copy a FILE object.<br />

10.5.1 Noncompliant Code Example<br />

This noncompliant code example can fail because a by-value copy of stdout is being used in the<br />

call to fputs():<br />

#include <br />

int main(void) {<br />

FILE my_stdout = *stdout;<br />

if (fputs("Hello, World!\n", &my_stdout) == EOF) {<br />

/* Handle error */<br />

}<br />

return 0;<br />

}<br />

When compiled under Microsoft Visual Studio 2013 and run on Windows, this noncompliant example<br />

results in an “access violation” at runtime.<br />

10.5.2 Compliant Solution<br />

In this compliant solution, a copy of the stdout pointer to the FILE object is used in the call to<br />

fputs():<br />

#include <br />

int main(void) {<br />

FILE *my_stdout = stdout;<br />

if (fputs("Hello, World!\n", my_stdout) == EOF) {<br />

/* Handle error */<br />

}<br />

return 0;<br />

}<br />

<strong>SEI</strong> <strong>CERT</strong> C <strong>Coding</strong> <strong>Standard</strong>: Rules for Developing Safe, Reliable, and Secure Systems 299<br />

Software Engineering Institute | Carnegie Mellon University<br />

[DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!