On Mon, 29 Jan 2024, David Laight wrote: > ... > > > I'm sure that the safest return for 'truncated' is the buffer length. > > > The a series of statements like: > > > buf += xxx(buf, buf_end - buf, .....); > > > can all be called with a single overflow check at the end. > > > > > > Forget the check, and the length just contains a trailing '\0' > > > which might cause confusion but isn't going to immediately > > > break the world. > > > > snprintf() does this and has been proven to cause buffer-overflows. > > There have been multiple articles authored describing why using > > snprintf() is not generally a good idea for the masses including the 2 > > linked in the commit message: > > snprintf() returns the number of bytes that would have been output [1]. > I'm not suggesting that, or not terminating the buffer. > Just returning the length including the '\0' (unless length was zero). > This still lets the code check for overflow but isn't going to > generate a pointer outside the buffer if used to update a pointer.
I see. Well I'm not married to my solution. However, I am convinced that the 2 solutions currently offered can be improved upon. If you or anyone else has a better solution, I'd be more than happy to implement and switch to it. Let me have a think about the solution you suggest and get back to you. > [1] I'm pretty certain this is because the original libc version > of sprintf() allocated a FILE structure on stack (fully buffered) > and called fprintf(). > snprintf() would have been done the same way but with something > to stop the buffer being flushed. Interesting. Thanks for the background. -- Lee Jones [李琼斯]