bug in mpz_urandomm
Torbjorn Granlund
tg at swox.com
Mon Apr 6 15:44:15 CEST 2009
Pierrick Gaudry <pierrick.gaudry at gmail.com> writes:
Section 3.4 of the manual says:
" GMP lets you use the same variable for both input and output in one
call."
And in Section 5.13, there is no exception for mpz_urandomm(). However
the implementation (in 4.2.4, at least), does not allow the first
parameter (the result) to be the third one (the bound). See for instance
the line 72 of mpz/urandomm.c that compares n and rp, but n can be
clobbered just the line before, if it's an alias to rp.
So I think this is a bug in the code, or in the documentation (I have no
objection to mpz_urandomm() not allowing aliases, but this should be
mentioned).
Please try this patch:
diff -r b73bf2b62dd4 mpz/urandomm.c
--- a/mpz/urandomm.c Wed Mar 11 23:49:29 2009 +0100
+++ b/mpz/urandomm.c Mon Apr 06 15:43:50 2009 +0200
@@ -34,6 +34,7 @@
int count;
int pow2;
int cmp;
+ TMP_DECL;
size = ABSIZ (n);
if (size == 0)
@@ -65,18 +66,29 @@
/* Clear last limb to prevent the case in which size is one too much. */
rp[size - 1] = 0;
+ TMP_MARK;
+ np = PTR (n);
+ if (rop == n)
+ {
+ mp_ptr tp;
+ tp = TMP_ALLOC_LIMBS (size);
+ MPN_COPY (tp, np, size);
+ np = tp;
+ }
+
count = MAX_URANDOMM_ITER; /* Set iteration count limit. */
do
{
_gmp_rand (rp, rstate, nbits);
- MPN_CMP (cmp, rp, PTR (n), size);
+ MPN_CMP (cmp, rp, np, size);
}
while (cmp >= 0 && --count != 0);
if (count == 0)
/* Too many iterations; return result mod n == result - n */
- mpn_sub_n (rp, rp, PTR (n), size);
+ mpn_sub_n (rp, rp, np, size);
MPN_NORMALIZE (rp, size);
SIZ (rop) = size;
+ TMP_FREE;
}
--
Torbjörn
More information about the gmp-bugs
mailing list