Skip to content

Commit

Permalink
Fix possible UB in the sum_string_vector function (TypeTools.hpp) (#893)
Browse files Browse the repository at this point in the history
Fixes #892 Undefined behavior in comparison of doubles.
  • Loading branch information
trokhymchuk authored Jun 27, 2023
1 parent a1135bb commit dce7983
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
11 changes: 4 additions & 7 deletions include/CLI/TypeTools.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1652,13 +1652,10 @@ inline std::string sum_string_vector(const std::vector<std::string> &values) {
output.append(arg);
}
} else {
if(val <= static_cast<double>((std::numeric_limits<std::int64_t>::min)()) ||
val >= static_cast<double>((std::numeric_limits<std::int64_t>::max)()) ||
std::ceil(val) == std::floor(val)) {
output = detail::value_string(static_cast<int64_t>(val));
} else {
output = detail::value_string(val);
}
std::ostringstream out;
out.precision(16);
out << val;
output = out.str();
}
return output;
}
Expand Down
3 changes: 2 additions & 1 deletion tests/AppTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <complex>
#include <cstdint>
#include <cstdlib>
#include <limits>

TEST_CASE_METHOD(TApp, "OneFlagShort", "[app]") {
app.add_flag("-c,--count");
Expand Down Expand Up @@ -828,7 +829,7 @@ TEST_CASE_METHOD(TApp, "SumOptFloat", "[app]") {

run();

CHECK(0.6 == val);
CHECK(std::fabs(0.6 - val) <= std::numeric_limits<double>::epsilon());
}

TEST_CASE_METHOD(TApp, "SumOptString", "[app]") {
Expand Down

0 comments on commit dce7983

Please sign in to comment.