From 8d56fe688b6ca70a28dfcb733f7ac1b8fcd26eb4 Mon Sep 17 00:00:00 2001 From: Jim Meyering Date: Mon, 30 Nov 2015 21:17:20 -0800 Subject: [PATCH] folly/Conv.h: estimateSpaceNeeded: avoid undefined behavior Summary: Do not negate signed numbers like INT_MIN or INTMAX_MIN, since that would evoke undefined behavior. Otherwise, the test (below) would fail with this run-time error: [ RUN ] Conv.Integral2String folly/Conv.h:521:47: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself Reviewed By: markisaa Differential Revision: D2704195 fb-gh-sync-id: 4036437fb972109672004163880078127e7df797 --- folly/Conv.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/folly/Conv.h b/folly/Conv.h index 8fdaef3b..ca6cbddf 100644 --- a/folly/Conv.h +++ b/folly/Conv.h @@ -513,7 +513,10 @@ typename std::enable_if< size_t>::type estimateSpaceNeeded(Src value) { if (value < 0) { - return 1 + digits10(static_cast(-value)); + // When "value" is the smallest negative, negating it would evoke + // undefined behavior, so, instead of writing "-value" below, we write + // "~static_cast(value) + 1" + return 1 + digits10(~static_cast(value) + 1); } return digits10(static_cast(value)); -- 2.34.1