printf appends null terminator to formatted output
acesme opened this issue · 4 comments
Hello,
Thank you for the fantastic work.
Should printf append a null terminator at the end of the formatted output? The standard seems to be unclear about this. The only statement I could find in the c11 standard regarding this is "The fprintf function returns when the end of the format string is encountered." [§7.21.6.1.2] (according to the standard, printf is equivalent to fprintf except for the first argument).
Hello @acesme ,
thank you for your comment!
As a matter of fact, it's a really good question. I would say (or suggest) it shouldn't.
In the moment, the low level _putchar()
function is responsible for the printf()
output, so any \0 could be filtered out easily.
Normally the plain native printf()
is used to output strings to the screen or a terminal and a terminator isn't needed or even unwanted.
Have to check it... Any other opinions/suggestions here?
Yes, it is simple to filter out the final '\0'
in the _putchar()
implementation.
It is also possible (albeit a little hacky) to fix this on 653rd row of printf.c by checking if out == _out_char
and opting to not append the '\0'
(or something like that).
I have no other suggestions that I can think of for now.
I think, it's better to "fix" this in _out_char() itself, so other output functions won't get any penalty, something like
static inline void _out_char(char character, char* buffer, size_t idx, size_t maxlen)
{
(void)buffer; (void)idx; (void)maxlen;
if (character) {
_putchar(character);
}
}