Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does write() write if null terminator is already reached?

Tags:

c

string

nul

For write(fd[1], string, size) - what would happen if string is shorter than size?

I looked up the man page but it doesn't clearly specify that situation. I know that for read, it would simply stop there and read whatever string is, but it's certainly not the case for write. So what is write doing? The return value is still size so is it appending null terminator? Why doesn't it just stop like read.

like image 462
Xufeng Avatar asked Mar 20 '23 08:03

Xufeng


1 Answers

When you call write(), the system assumes you are writing generic data to some file - it doesn't care that you have a string. A null-terminated string is seen as a bunch of non-zero bytes followed by a zero byte - the system will keep writing out until it's written size bytes.

Thus, specifying size which is longer than your string could be dangerous. It's likely that the system is reading data beyond the end of the string out your file, probably filled with garbage data.

like image 198
Chris McGrath Avatar answered Apr 07 '23 11:04

Chris McGrath