My own favourite random() in the wild bug is one that I've come across many many times:
/* Generate a random number 0...5 inclusive */
int r = random() % 6;
The problem is that this results in a bias towards certain values, because the random() return space is probably not a whole multiple of the number you are modding. It's easier if you think what would happen if RAND_MAX were "10". Then the results 0,1,2,3,4 each have two opportunities of being selected for r, but "5" only has one. So 5 is half as likely as any other number. Terrible!Using float/double random()'s don't always help either, because floating point multiplication has non-uniform errors. Instead, what you really need is:
int random_n(int top) {
if (top <= 0) {
return -1;
}
while(1) {
int r = random(top);
if (r < (RAND_MAX - (RAND_MAX % top))) {
return r;
}
}
return -1;
}
Although it's better to replace random() itself with something that uses real entropy.