@@ -5098,8 +5098,10 @@ mpz_montgomery_reduce(mpz_ctx_t *ctx, mpz_t *result,
|
5098 | 5098 | size_t k = n->sz; /* Number of limbs in modulus */ |
5099 | 5099 | size_t x_len = x->sz; |
5100 | 5100 | |
5101 | | -/* Allocate workspace: need k+1 extra limbs for the product accumulation */ |
5102 | | -size_t work_size = x_len + k + 2; |
| 5101 | +/* Allocate workspace: Montgomery reduction writes k limbs at work[i] for i=0..k-1, |
| 5102 | + * so the maximum index accessed is work[2k-1] (from carry propagation). |
| 5103 | + * We need at least 2k limbs, plus extra if x_len > k. */ |
| 5104 | +size_t work_size = (x_len > k) ? (x_len + k + 2) : (2 * k + 2); |
5103 | 5105 | size_t pool_state = pool_save(ctx); |
5104 | 5106 | |
5105 | 5107 | mp_limb *work = NULL; |
@@ -5263,6 +5265,7 @@ bint_set(mpz_ctx_t *ctx, struct RBigint *b, mpz_t *x)
|
5263 | 5265 | } |
5264 | 5266 | else { |
5265 | 5267 | RBIGINT_SET_HEAP(b); |
| 5268 | +mpz_init(ctx, &b->as.heap); /* Initialize before mpz_move */ |
5266 | 5269 | mpz_move(ctx, &b->as.heap, x); |
5267 | 5270 | } |
5268 | 5271 | } |
|