1
0
mirror of https://github.com/CLIUtils/CLI11.git synced 2025-05-05 14:43:52 +00:00

Fix possible UB in the sum_string_vector function (TypeTools.hpp) (#893)

Fixes #892 Undefined behavior in comparison of doubles.
This commit is contained in:
Artem Trokhymchuk 2023-06-28 02:53:34 +03:00 committed by GitHub
parent a1135bb30c
commit dce7983efa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 8 deletions

View File

@ -1652,13 +1652,10 @@ inline std::string sum_string_vector(const std::vector<std::string> &values) {
output.append(arg); output.append(arg);
} }
} else { } else {
if(val <= static_cast<double>((std::numeric_limits<std::int64_t>::min)()) || std::ostringstream out;
val >= static_cast<double>((std::numeric_limits<std::int64_t>::max)()) || out.precision(16);
std::ceil(val) == std::floor(val)) { out << val;
output = detail::value_string(static_cast<int64_t>(val)); output = out.str();
} else {
output = detail::value_string(val);
}
} }
return output; return output;
} }

View File

@ -11,6 +11,7 @@
#include <complex> #include <complex>
#include <cstdint> #include <cstdint>
#include <cstdlib> #include <cstdlib>
#include <limits>
TEST_CASE_METHOD(TApp, "OneFlagShort", "[app]") { TEST_CASE_METHOD(TApp, "OneFlagShort", "[app]") {
app.add_flag("-c,--count"); app.add_flag("-c,--count");
@ -828,7 +829,7 @@ TEST_CASE_METHOD(TApp, "SumOptFloat", "[app]") {
run(); run();
CHECK(0.6 == val); CHECK(std::fabs(0.6 - val) <= std::numeric_limits<double>::epsilon());
} }
TEST_CASE_METHOD(TApp, "SumOptString", "[app]") { TEST_CASE_METHOD(TApp, "SumOptString", "[app]") {