Bug in Newlib's snprintf implementation

Corinna Vinschen vinschen@redhat.com
Fri Feb 23 10:57:00 GMT 2018


On Feb 23 05:33, Jeffrey Walton wrote:
> On Fri, Feb 23, 2018 at 5:21 AM, Corinna Vinschen <vinschen@redhat.com> wrote:
> > On Feb 23 05:12, Jeffrey Walton wrote:
> >> On Fri, Feb 23, 2018 at 4:43 AM, Corinna Vinschen <vinschen@redhat.com> wrote:
> >> > Slight correction: snprintf returns the size of the string it would
> >> > have produced if it hadn't truncated the output.  So a size value
> >> > of 4 ("test" would have been the desired result) is correct.
> >>
> >> I don't believe this is correct. The string of 'test' and the NULL
> >> requires 5, not 4. 4 indicates truncation.
> >
> > 4 is correct:
> >
> >> According to the man page (https://linux.die.net/man/3/snprintf):
> >>
> >> <SNIP>
> >> RETURN VALUE
> >>
> >> Upon successful return, these functions return the number of
> >> characters printed (excluding the null byte used to end output to
> >> strings).
> >>
> >> The functions snprintf() and vsnprintf() do not write more than size
> >> bytes (including the terminating null byte ('\0')). If the output was
> >> truncated due to this limit then the return value is the number of
> >> characters (excluding the terminating null byte) which would have been
> >               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> >
> >> written to the final string if enough space had been available. Thus,
> >> a return value of size or more means that the output was truncated.
> >> (See also below under NOTES.)
> >> </SNIP>
> >
> > The desired result is a string with 4 chars, "test".  The return value
> > reflects the desired result, *excluding* the NUL, if the truncation
> > wouldn;t have been necessary.  That's 4.
> 
> Perhaps I am missing something obvious, so please forgive my ignorance.
> 
> The code is going to produce a string 'tes\0', not 'test\0'. The
> string 'tes\0' is truncated, and the return value of 4 indicates that.
> The return value should have been 5.

But that would count the trailing NUL, which it must not.  Consider

  snprintf (buf, 3, "%s", "1234567890");

Written to buf: "12\0"
Return value: 10

That's what the snprintf man page means with:

  "Thus, a return value of `size' or more means that the output was
   truncated."


Corinna

-- 
Corinna Vinschen
Cygwin Maintainer
Red Hat
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://sourceware.org/pipermail/newlib/attachments/20180223/f65e6827/attachment.sig>


More information about the Newlib mailing list