Skip to content

Commit 6acfc06

Browse files
committed
Raise error if random(ZZ) called w/ nonpositive height
Previously, we silently ignored the negative sign when height was negative, but this was undocumented, and crashed when the height was zero.
1 parent 8f4c663 commit 6acfc06

File tree

3 files changed

+16
-11
lines changed

3 files changed

+16
-11
lines changed

M2/Macaulay2/d/interface.dd

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ setupfun("testCatch",testCatch);
4747

4848
export rawRandomZZ(e:Expr):Expr := (
4949
when e
50-
is Nothing do toExpr(Ccode(ZZ, "rawRandomInteger(", "NULL)"))
51-
is maxN:ZZcell do toExpr(Ccode(ZZ, "rawRandomInteger(", maxN.v, ")"))
50+
is Nothing do toExpr(Ccode(ZZorNull, "rawRandomInteger(", "NULL)"))
51+
is maxN:ZZcell do toExpr(Ccode(ZZorNull, "rawRandomInteger(", maxN.v, ")"))
5252
else WrongArgZZ());
5353
setupfun("rawRandomZZ",rawRandomZZ);
5454
export rawFareyApproximation(e:Expr):Expr := (

M2/Macaulay2/e/interface/random.cpp

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,11 @@ int32_t rawRandomInt(int32_t max)
5656
void rawSetRandomInteger(mpz_ptr result, gmp_ZZ maxN)
5757
/* if height is the null pointer, use the default height */
5858
{
59-
if (maxN == nullptr)
60-
mpz_urandomm(result, state, maxHeight);
61-
else if (1 != mpz_sgn(maxN))
62-
{
63-
mpz_set_si(result, 0);
64-
}
65-
else
66-
mpz_urandomm(result, state, maxN);
59+
if (maxN == nullptr) maxN = maxHeight;
60+
if (mpz_cmp_si(maxN, 0) <= 0)
61+
throw exc::engine_error("expected a positive height");
62+
63+
mpz_urandomm(result, state, maxN);
6764
}
6865

6966
gmp_ZZ rawRandomInteger(gmp_ZZ maxN)
@@ -72,7 +69,12 @@ gmp_ZZ rawRandomInteger(gmp_ZZ maxN)
7269
mpz_ptr result = getmemstructtype(mpz_ptr);
7370
mpz_init(result);
7471

75-
rawSetRandomInteger(result, maxN);
72+
try {
73+
rawSetRandomInteger(result, maxN);
74+
} catch (const exc::engine_error& e) {
75+
ERROR(e.what());
76+
return nullptr;
77+
}
7678

7779
mpz_reallocate_limbs(result);
7880
return result;

M2/Macaulay2/tests/normal/randommat.m2

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ assert isSurjective random(R^3,R^6,MaximalRank=>true)
3434
assert(random(ZZ^2, ZZ^2, MaximalRank => true) - id_(ZZ^2) != 0)
3535
assert(random(QQ^2, QQ^2, MaximalRank => true) - id_(QQ^2) != 0)
3636
assert(random(R^2, R^2, MaximalRank => true) - id_(R^2) != 0)
37+
38+
-- used to crash M2 (#2089)
39+
assert try random(ZZ^2, ZZ^2, Height => 0) then false else true

0 commit comments

Comments
 (0)