c - Does '\0' appear naturally in text files? -


i encountered annoying bug today string (stored char[]) printed junk @ end. string suppose printed (using arduino print/write functions) correct (it correctly included \r , \n). however, there junk printed @ end.

i allocated element store '\0' after '\r' , '\n' (which last 2 characters in string printed). then, print() printed string correctly. seems '\0' used indicate print() function string had terminated (i remember reading in kernighan's c).

this bug appeared in code reads text file. occurred me did not encounter '\0' @ when designed code. leads me believe '\0' has no practical use in text editors , merely used print functions. correct?

c strings terminated nul byte ('\0') - implicitly appended string literals in double quotes, , used terminator standard library functions operating on strings. follows c strings can not contain '\0' terminator in between other characters, since there no way tell whether actual end of string or not.

(of course handle strings in c language other c strings - e.g., adding integer record length of string make terminator unnecessary, such strings not interoperable functions expecting c strings.)

a "text file" in general not governed c standard, , user of c program conceivably give file containing nul byte input c program (which unable handle "correctly" above reasons if read file c strings). however, nul byte has no valid reason existing in plain text file, , may considered @ least de facto standard text files not contain nul byte (or other control characters, might break transmission of text through terminals or serial protocols).

i argue acceptable (though not necessary!) limitation program working on plain text input not guarantee correct output if there nul bytes in input. however, programmer should aware of possibility regardless of whether treated correctly, , not allow cause undefined behaviour in program. user input, should considered "unsafe" in sense can contain (e.g., maliciously formed on purpose).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -