The POSIX standard defines the write() interface as follows [1].
ssize_t write (int filedes, const void *buffer, size_t size);
The write function writes up to size bytes from buffer to the file with descriptor filedes. The data in buffer is not necessarily a character string and a null character is output like any other character.
The definition does not state that the write() function will stop copying characters into the file if a null character is encountered. Therefore, when writing a C string in to a file using the write() function, always use the size of the buffer string as the size parameter.
Noncompliant Code Example
In the following piece of code, the size of the buffer is stored in size1, but size2 number of characters are written in to the file. If size2 is greater than size1, write() will not stop copying characters at the null character.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main(){
char *buffer = NULL;
long size1, size2;
int filedes;
filedes = open("out.txt", O_CREAT | O_WRONLY);
if (filedes < 0)
return 0;
buffer = (char *)calloc(1, size1);
if (!buffer)
return 0;
write(filedes, buffer, size2);
free(buffer);
buffer = NULL;
close(filedes);
return 0;
}
Compliant Code Example
The following code will ensure that the right number of characters are written in to the file.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main(){
char *buffer = NULL;
long size1, size2;
int filedes;
filedes = open("out.txt", O_CREAT | O_WRONLY);
if (filedes < 0)
return 0;
buffer = (char *)calloc(1, size1);
if (!buffer)
return 0;
/* ...
* Accept characters in to the buffer
* Check for buffer overflow
* ...
*/
size2 = strlen(buffer);
write(filedes, buffer, size2);
free(buffer);
buffer = NULL;
close(filedes);
return 0;
}
References
[1] http://www.gnu.org/software/libc/manual/html_node/I_002fO-Primitives.html#I_002fO-Primitives![]()