I found this code snippet in an old and dusty project:
int *p = (int*)malloc(sizeof(p)); // generate random number
free(p); // free up space
int rand = p%3; // get random value in between 0-2
Apart from it being bad style and unnecessary as we got srand in the C standard lib, what is the actual randomness of the return value?
While true randomness is not needed in the context it is used, I tested it several times for 99999999 iterations each and for every single test run rand == 0
was less often true than both other cases (rand == 1
and rand == 2
).
One example:
rand == 0
: true 27343746 times out of 99999999rand == 1
: true 36328138 times out of 99999999rand == 2
: true 36328115 times out of 99999999
Aucun commentaire:
Enregistrer un commentaire