Skip to content

Commit 8a80f41

Browse files
JKaniarzslouken
authored andcommitted
Added check for n<0 in SDL_rand_n()
1 parent 38cac04 commit 8a80f41

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/stdlib/SDL_random.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,14 @@ Sint32 SDL_rand_n(Sint32 n)
6767
// fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit
6868
// result. Shift right by 32 to get the 31 bit integer that we want.
6969

70+
if (n < 0) {
71+
// The algorithm looks like it works for numbers < 0 but it has an
72+
// infintesimal chance of returning a value out of range.
73+
// Returning -SDL_rand_n(abs(n)) blows up at INT_MIN instead.
74+
// It's easier to just say no.
75+
return 0;
76+
}
77+
7078
// On 32-bit arch, the compiler will optimize to a single 32-bit multiply
7179
Uint64 val = (Uint64)SDL_rand_bits() * n;
7280
return (Sint32)(val >> 32);

0 commit comments

Comments
 (0)