lmi
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [lmi] Wouldn't this be far beyond pedantic?


From: Vadim Zeitlin
Subject: Re: [lmi] Wouldn't this be far beyond pedantic?
Date: Mon, 13 Jun 2022 18:26:41 +0200

On Mon, 13 Jun 2022 16:09:40 +0000 Greg Chicares <gchicares@sbcglobal.net> 
wrote:

GC> I was thinking of using '-Wformat-truncation=2', but it warns whenever
GC> std::snprintf() might truncate, which is...always, unless the second
GC> (buffer-size) argument is 0. And it warns even though I immediately
GC> assert that the returned length is greater than zero and less than the
GC> buffer size. However...
GC> 
GC> Here's a workaround that avoids the warning:
GC>  - first, call snprintf() using zero just to determine the length;
GC>  - then,  call snprintf() again, using the length just determined.
GC> Isn't this a change that any sane reviewer would reject, because the
GC> assertions are ideal and comprehensive, and calling snprintf() twice
GC> is ludicrously inefficient? Or is it the case that this patch shows
GC> exactly how snprintf() ought always to be used, and I've simply
GC> failed to understand it?

 Yes, this is how snprintf() is supposed to be always used, although in
practice there are plenty of cases when you know the size in advance and
can be sure that it never overflows. But, undoubtedly, there are also many
cases when people thought they knew the size, but they actually didn't and
it did overflow.

 Personally I'd rather get rid of snprintf() at all than spend time on
trying to fix warnings related to it. The best general alternative to it
is std::format(), which can be easily used in any environment right now by
using fmt library, which implements the same API (and was the base for the
standardization).

 In some special cases other alternatives could be preferable, e.g.
std::to_string() for simple locale-dependent number formatting (probably
not useful for lmi) or std::to_chars() for not simple at all but very fast
number formatting (which probably could be useful for lmi).

 But, again, the best solution is in any case to stop using printf-like
format strings completely and switch to format() which provides
compile-time format string checks all on its own. BTW, note that this can
be done progressively, by mechanically replacing the existing calls to
snprintf() with fmt::printf(), which uses the same format string syntax,
and then replacing them, and all the uses of std::ostringstream, with
std::format().

 Regards,
VZ

Attachment: pgpqU3uYQrMPk.pgp
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]