From 52d95e72ed7cd5c4a62c1aac019d5d171073bdd2 Mon Sep 17 00:00:00 2001 From: Lephe Date: Fri, 9 Oct 2020 09:17:48 +0200 Subject: [PATCH] stdlib: force rand() to return a non-negative number Negative numbers come with tricky modulus results and are excluded from the return values of the standard rand(). --- include/gint/std/stdlib.h | 4 +++- src/std/tinymt32/rand.c | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/gint/std/stdlib.h b/include/gint/std/stdlib.h index ec4ad6f..99cf988 100644 --- a/include/gint/std/stdlib.h +++ b/include/gint/std/stdlib.h @@ -19,10 +19,12 @@ void *calloc(size_t nmemb, size_t size); /* realloc(): Reallocate dynamic memory */ void *realloc(void *ptr, size_t size); +#define RAND_MAX 0x7fffffff + /* srand(): Seed the PRNG */ void srand(unsigned int seed); -/* rand(): Generate a pseudo-random number */ +/* rand(): Generate a pseudo-random number between 0 and RAND_MAX */ int rand(void); #endif /* GINT_STD_STDLIB */ diff --git a/src/std/tinymt32/rand.c b/src/std/tinymt32/rand.c index 9800272..d8d6833 100644 --- a/src/std/tinymt32/rand.c +++ b/src/std/tinymt32/rand.c @@ -10,5 +10,5 @@ void srand(unsigned int seed) int rand(void) { - return tinymt32_generate_uint32(&random); + return tinymt32_generate_uint32(&random) & 0x7fffffff; }