mruby-pack: avoid integer overflow in pack_hex buffer calculation

rewrite ceiling division to avoid signed overflow. the expression
(count + 1) / 2 triggers undefined behavior when count == INT_MAX.
use count / 2 + (count & 1) instead, which computes the same result
without intermediate overflow.

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Yukihiro "Matz" Matsumoto
2025-11-19 15:34:32 +09:00
parent 3f2611ebcd
commit 2da01c607f
+2 -1
View File
@@ -1009,7 +1009,8 @@ pack_hex(mrb_state *mrb, mrb_value src, mrb_value dst, mrb_int didx, int count,
}
/* calculate output buffer size needed - one byte per two hex chars */
int output_bytes = (count + 1) / 2;
/* use count/2 + (count&1) to avoid overflow when count == INT_MAX */
int output_bytes = count / 2 + (count & 1);
dst = str_len_ensure(mrb, dst, didx + output_bytes);
char *dptr = RSTRING_PTR(dst) + didx;
char *dptr0 = dptr;