Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: I changed nitem to nmemb in the C11 quote and following text

C99 The C standard defines the fwrite() function as follows [ISO/IEC 9899:19992011]:

Synopsis 

size_t fwrite(const void *restrict ptr, size_t size, size_t nitemsnmemb, FILE *restrict stream);

Description

The fwrite() function shall writewrites, from the array pointed to by ptr, up to nitems nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls shall be calls are made to the fputc() function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file - position indicator for the stream (if defined) shall be  is advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file - position indicator for the stream is unspecifiedindeterminate.

The definition does not state that the fwrite() function will stop copying characters into the file if a null character is encountered. Therefore, when writing a null-terminated byte string to a file using the fwrite() function, always use the length of the string plus 1 (to account for the null character) as the nitems the nmemb parameter.

Noncompliant Code Example

...

CERT C++ Secure Coding Standard: FIO18-CPP. Never expect write() to terminate the writing process at a null character

ISO/IEC 9899:1999 Section 2011 Section 7.1921.8.2, "The fwrite function"

Bibliography

http://www.opengroup.org/onlinepubs/009695399/functions/fwrite.html

...