Re: [PATCH] x86/lib: Fix num_digits() signed overflow for INT_MIN

From: David Desobry

Date: Tue Jan 20 2026 - 16:28:13 EST


Fair point! I've sent a v2 that replaces the loop with a switch statement (using GCC ranges). It's faster, handles INT_MIN properly via an unsigned cast, and I've cleaned up that mobile-submission comment while I was at it.

Le 20/01/2026 à 17:23, H. Peter Anvin a écrit :
On January 20, 2026 1:42:58 AM PST, David Desobry <david.desobry@xxxxxxxxxxxxx> wrote:
In num_digits(), the negation of the input value "val = -val"
causes undefined behavior when val is INT_MIN, as its absolute
value cannot be represented as a signed 32-bit integer.

This leads to incorrect results (returning 2 instead of 11).
By promoting the value to long long before negation, we ensure
the absolute value is correctly handled.

Signed-off-by: David Desobry <david.desobry@xxxxxxxxxxxxx>
---
arch/x86/lib/misc.c | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/arch/x86/lib/misc.c b/arch/x86/lib/misc.c
index 40b81c338ae5..c975db6ccb9f 100644
--- a/arch/x86/lib/misc.c
+++ b/arch/x86/lib/misc.c
@@ -8,15 +8,16 @@
*/
int num_digits(int val)
{
+ long long v = val;
long long m = 10;
int d = 1;

- if (val < 0) {
+ if (v < 0) {
d++;
- val = -val;
+ v = -v;
}

- while (val >= m) {
+ while (v >= m) {
m *= 10;
d++;
}
That has got to be the dumbest possible implementation of that task, bug or no bug.

A switch statement would be simpler and faster.