lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On this particular platform, RAND_MAX is bigger than a regular int. Unless
> the result of rand() is cast to an unsigned int, it can overflow and return
> negative numbers.
> 
> +++ lmathlib.c 2010-03-09 13:20:09.000000000 -0800
> @@ -181,7 +181,7 @@
>  static int math_random (lua_State *L) {
>    /* the `%' avoids the (rare) case of r==1, and is needed also because on
>       some systems (SunOS!) `rand()' may return a value larger than RAND_MAX
> */
> -  lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
> +  lua_Number r = (lua_Number)(((unsigned int)rand())%RAND_MAX) /
> (lua_Number)RAND_MAX;
>    switch (lua_gettop(L)) {  /* check number of arguments */
>      case 0: {  /* no arguments */
>        lua_pushnumber(L, r);  /* Number between 0 and 1 */

There is something strange here. If RAND_MAX is bigger than a regular int,
then its type should be long or unsigned int (or anything else larger than
an int). By the "usual arithmetic convertions", the result of random should
be converted implicitly to that other type.

-- Roberto