RAND_MAX is power of 2

Steve Kargl sgk at troutmask.apl.washington.edu
Wed Jun 7 19:00:23 UTC 2017


On Wed, Jun 07, 2017 at 02:34:48PM -0400, Littlefield, Tyler wrote:
> All:
> 
> I'm trying to find another solution to this and port this server to
> FreeBSD. So far the only thing holding me up is that they want RAND_MAX
> to be a power of 2, and I don't want to just change things without
> knowing what I'm changing. Is there a reason for this?

svn log -r 252608 /usr/src/include/stdlib.h

r252608 | ache | 2013-07-03 14:21:54 -0700 (Wed, 03 Jul 2013) | 15 lines

1) POSIX requires rand(3) return values to be in the [0, RAND_MAX] range,
but ACM formula we use have internal state (and return value) in the
[1, 0x7ffffffe] range, so our RAND_MAX (0x7fffffff) is never reached
because it is off by one, zero is not reached too.

Correct both RAND_MAX and rand(3) return value, shifting last one
to the 0 by 1 subtracted, resulting POSIXed [0, 0x7ffffffd(=new RAND_MAX)]
range.

2) Add a checks for not overflowing on too big seeds. It may happens on
the machines, where sizeof(unsigned int) > 32 bits.

Reviewed by:    bde [1]
MFC after:      2 weeks

-- 
Steve
20170425 https://www.youtube.com/watch?v=VWUpyCsUKR4
20161221 https://www.youtube.com/watch?v=IbCHE-hONow


More information about the freebsd-hackers mailing list