lmi
[Top][All Lists]
Advanced

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

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


From: Greg Chicares
Subject: [lmi] Wouldn't this be far beyond pedantic?
Date: Mon, 13 Jun 2022 16:09:40 +0000
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Thunderbird/91.8.0

I was thinking of using '-Wformat-truncation=2', but it warns whenever
std::snprintf() might truncate, which is...always, unless the second
(buffer-size) argument is 0. And it warns even though I immediately
assert that the returned length is greater than zero and less than the
buffer size. However...

Here's a workaround that avoids the warning:
 - first, call snprintf() using zero just to determine the length;
 - then,  call snprintf() again, using the length just determined.
Isn't this a change that any sane reviewer would reject, because the
assertions are ideal and comprehensive, and calling snprintf() twice
is ludicrously inefficient? Or is it the case that this patch shows
exactly how snprintf() ought always to be used, and I've simply
failed to understand it?

(Well, maybe it would suffice to assert
-  0 < length && length < buffer_size
+  0 < length && length <= buffer_size
or even to allow zero in circumstances where it would be legitimate
to write zero characters--so instead of calling the assertions used
"ideal", I should claim that they're absolutely sufficient, though
perhaps stricter than necessary.)

--8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<--
diff --git a/duff_fmt.hpp b/duff_fmt.hpp
index 83f3c17f4..94b236d0e 100644
--- a/duff_fmt.hpp
+++ b/duff_fmt.hpp
@@ -49,8 +49,9 @@ inline std::string duff_fmt(double value, int decimals)
     char* q = out_buf;
 
     // Use '#' to force a decimal point unless infinite or NaN.
-    int const length = std::snprintf(p, buffer_size, "%#.*f", decimals, value);
+    int const length = std::snprintf(p, 0, "%#.*f", decimals, value);
     LMI_ASSERT(0 < length && length < buffer_size);
+    std::snprintf(p, buffer_size, "%#.*f", decimals, value);
     LMI_ASSERT(lmi::sstrlen(p) == length);
 
     char const*const r = std::strchr(p, '.');
--8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<--


reply via email to

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