As multiple questions on here also point out, you can printf
a nonterminated string by formatting with a precision as maximum length to print. Something like
printf("%.*s\n", length, str);
will print length
chars starting at str
(or until the first 0 byte).
As pointed out here by jonathan-leffler, this is specified by posix here. And when reading the doc I discovered it actually never states this should work (or I couldn't find it) , as "The ‘%s’ conversion prints a string." and "A string is a null-terminated array of bytes [...] ". The regard about the precision states "A precision can be specified to indicate the maximum number of characters to write;".
My interpretation would be that the line above is actually undefined behavior, but because printf
's implementation is efficient it doesn't read more than it writes.
So my question is: Is this interpretation correct and
TLDR: Should I stop using this printf trick when trying to be posix compliant as there exists an implementation where this might cause a buffer-overrun?