Hi Vincent, Siddhesh, On 3/20/23 13:05, Siddhesh Poyarekar wrote: > On 2023-03-19 19:07, Vincent Lefevre wrote: >> On 2023-03-19 10:45:59 -0400, manfred via Libc-alpha wrote: >>> All of that said, back to the OP case I would not pass INT_MAX to snprintf. >>> If I have a situation wherein I know that the buffer is large enough, but I >>> don't know its exact size, I'd use sprintf and be done with it. (I'm sure >>> that the actual code is more elaborate than this, but still) >> >> In simple code, probably. But in actual code, it may be more natural >> to use snprintf. Something like that: >> >> snprintf(buf, checked ? SIZE_MAX : n, "%s", s); >> >> The function may not know the buffer size if `checked` is true, >> so that it uses a known bound. Thanks to common code factorized, >> this is more readable than >> >> if (checked) >> sprintf (buf, "%s", s); >> else >> snprintf(buf, n, "%s", s); >> >> in particular in the cases where the format string is complex. That pattern looks like _FORTIFY_SOURCE, doesn't it? If so, the correct action would be to call sprintf(3) and rely on the compiler to do the checks. snprintf(3) should be called when you can't guarantee at coding time if the array is possibly overrun. If you can guarantee that, then call sprintf(3), and the compiler will confirm. Cheers, Alex > > If your application requires such patterns then it really needs an > additional layer of abstraction or maybe a rethink on the pattern > itself. This is not something the C runtime should try to solve. > > I think on the glibc front it makes sense from a security perspective to > interpret this through POSIX than the C standard. Even if the C > standard is clarified to be contrary to POSIX and explicitly state that > n is not the size of the buffer (which would be a terrible mistake IMO), > I'd lean towards violating the C standard and conforming to POSIX instead. > > Sid -- GPG key fingerprint: A9348594CE31283A826FBDD8D57633D441E25BB5