...
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 plus 1 (for the null character) 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.
| Code Block |
|---|
|
#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.
| Code Block |
|---|
|
#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
| Wiki Markup |
|---|
\[1\] [http://www.gnu.org/software/libc/manual/html_node/I_002fO-Primitives.html#I_002fO-Primitives] |