Skip to content

Commit ba0d8f4

Browse files
committed
Fix overflow exception of the modulo operator (fix #1176)
1 parent 6864aa8 commit ba0d8f4

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/builtin.c

+4-2
Original file line numberDiff line numberDiff line change
@@ -396,9 +396,11 @@ static jv f_divide(jq_state *jq, jv input, jv a, jv b) {
396396
static jv f_mod(jq_state *jq, jv input, jv a, jv b) {
397397
jv_free(input);
398398
if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {
399-
if ((intmax_t)jv_number_value(b) == 0)
399+
intmax_t bi = (intmax_t)(jv_number_value(b));
400+
if (bi == 0)
400401
return type_error2(a, b, "cannot be divided (remainder) because the divisor is zero");
401-
jv r = jv_number((intmax_t)jv_number_value(a) % (intmax_t)jv_number_value(b));
402+
// Check if the divisor is -1 to avoid overflow when the dividend is INTMAX_MIN.
403+
jv r = jv_number(bi == -1 ? 0 : (intmax_t)(jv_number_value(a)) % bi);
402404
jv_free(a);
403405
jv_free(b);
404406
return r;

tests/jq.test

+4
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,10 @@ null
540540
null
541541
172
542542

543+
[(infinite, -infinite) % (1, -1)]
544+
null
545+
[0,0,0,0]
546+
543547
1 + tonumber + ("10" | tonumber)
544548
4
545549
15

0 commit comments

Comments
 (0)