pw_string: Fix signed integer overflow
std::abs() fails for the minimum valued integer, since its absolute
value cannot be represented as a signed integer. Cast to uint64_t before
negating the value to avoid this.
Fixes: b/298647705
Change-Id: I5102122814a77653e407bc8229bc6ea3d3091fbb
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/171839
Commit-Queue: Wyatt Hepler <hepler@google.com>
Reviewed-by: Ted Pudlik <tpudlik@google.com>
Pigweed-Auto-Submit: Wyatt Hepler <hepler@google.com>
diff --git a/pw_string/type_to_string.cc b/pw_string/type_to_string.cc
index b143bcb..bc4ce00 100644
--- a/pw_string/type_to_string.cc
+++ b/pw_string/type_to_string.cc
@@ -138,9 +138,10 @@
}
// Write as an unsigned number, but leave room for the leading minus sign.
- auto result =
- IntToString<uint64_t>(static_cast<uint64_t>(std::abs(value)),
- buffer.empty() ? buffer : buffer.subspan(1));
+ // Do not use std::abs since it fails for the minimum value integer.
+ const uint64_t absolute_value = -static_cast<uint64_t>(value);
+ auto result = IntToString<uint64_t>(
+ absolute_value, buffer.empty() ? buffer : buffer.subspan(1));
if (result.ok()) {
buffer[0] = '-';