This is the mail archive of the newlib@sourceware.org mailing list for the newlib project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Bug in Newlib's snprintf implementation


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

Attachment: signature.asc
Description: PGP signature


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]