A pseudo-random number generator will produce the same stream of numbers if seeded with the same seed. Every time srand
is called the stream will restart. You're using time
which is in seconds. If your function calls are within the same second, they'll get the same stream.
The first part of the solution is to only call srand
once at the start of the program. But this is only a partial solution. time
alone is a poor seed, and unfortunately, it's in all the tutorials. If the program is run in the same second it will get the same random numbers.
A better seed, on Unix, is to read from /dev/random
.
int main() {
FILE *fp = fopen("/dev/random", "r");
if( fp == NULL ) {
perror("Could not open /dev/random");
}
unsigned int seed;
fread(&seed, sizeof(seed), 1, fp);
srand(seed);
for( int i = 0; i < 10; i++ ) {
printf("%d\n", rand());
}
}
rand
is a very poor random number generator. If you need random numbers for security purposes, ones that nobody will be able to guess, use a proper cryptography library.