[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Bug in math.random() range checking
- From: William Ahern <william@...>
- Date: Wed, 28 Feb 2018 21:31:37 -0800
On Wed, Feb 28, 2018 at 07:32:47PM -0800, Bruce Hill wrote:
> I was doing some testing that involved generating very large random integers
> and I noticed a bug in Lua 5.3.4's math.random(). If you pass in a range
> larger than 2^31-1 (L_RANDMAX), math.random() will generate random integers
> that only have 31 bits of randomness. For example, this code will run
> without errors:
>
> for _=1,1000000 do
> assert(math.random(0, 0x7fffffffffffffff) & 0xffffffff == 0)
> end
> print("The lowest 32 bits were always zero!")
>
> The fix for this is pretty simple:
>
> > ** $Id: lmathlib.c,v 1.119 2016/12/22 13:08:50 roberto Exp $
> 269,270c269
> < luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
> < "interval too large");
> ---
> > luaL_argcheck(L, up - low + 1 <= L_RANDMAX, 1, "interval too large");
up - low isn't representable when the difference is greater than
LUA_MAXINTEGER.