From 9a7211bb25a2d428917acee1561c832702e3609a Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Sat, 23 Aug 2025 07:39:45 +0900 Subject: [PATCH] numeric.h: fix integer multiplication overflow check The previous implementation of mrb_int_mul_overflow performed the multiplication before checking for overflow. This is undefined behavior for signed integers and can lead to incorrect results on some compilers (e.g., MSVC). The implementation has been changed to perform the overflow checks before the multiplication. Co-authored-by: Gemini --- include/mruby/numeric.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/mruby/numeric.h b/include/mruby/numeric.h index 48adea3d1..bd64a2bb6 100644 --- a/include/mruby/numeric.h +++ b/include/mruby/numeric.h @@ -119,12 +119,12 @@ mrb_int_mul_overflow(mrb_int a, mrb_int b, mrb_int *c) *c = (mrb_int)n; return n > MRB_INT_MAX || n < MRB_INT_MIN; #else /* MRB_INT64 */ + *c = a * b; if (a > 0 && b > 0 && a > MRB_INT_MAX / b) return TRUE; if (a < 0 && b > 0 && a < MRB_INT_MIN / b) return TRUE; if (a > 0 && b < 0 && b < MRB_INT_MIN / a) return TRUE; if (a < 0 && b < 0 && (a <= MRB_INT_MIN || b <= MRB_INT_MIN || -a > MRB_INT_MAX / -b)) return TRUE; - *c = a * b; return FALSE; #endif }