Reputation: 8498
I'm attempting to pick random indexes from a array in C. The problem I'm having is that my random numbers aren't going from the range I expect (from 0 to 2047) as this example says that it will. Just from looking at the indexes I get it seems like I'm getting numbers from 1000-1200 instead of the desired range.
Here's the code which calls rand().
#define MAXPAGES 2048 // maximum number of processes in the system
//until we have a node, pick random indexes.
while(node == NULL){
table_index = rand() % MAXPAGES;
node = table[table_index];
if(node){
fprintf(stderr, "%d\n", table_index);
if(node->current_pages > 0) break;
else node = NULL;
}
}
I call srand only once in my main function.
int main(int argc, char** argv) {
int i;
int simulations = 100000;
// initialize the process hash table
if(argc > 1){
removal_algorithm = atoi(argv[1]);
if(argc == 3) simulations = atoi(argv[2]);
}
srand(time(NULL));
for (i = 0; i < MAXPAGES; i++) table[i] = NULL;
printf("Random replacement MMU simulation on %d simulations started\n", simulations);
Simulate(simulations);
printf("Random MMU simulation completed. only writing page faults:,");
printf("%d, read / write page faults: %d, total page faults: %d\n", read_miss, write_miss, read_miss + write_miss);
}
Example sequence.
1117
1069
1103
1118
1071
1117
1120
1092
1099
1116
1121
1122
1110
1116
1069
1113
1120
1117
1116
1071
1121
1094
1110
1119
1102
1117
1071
1108
1102
1099
1109
1109
1092
1109
1120
1108
1094
1101
1122
1086
1110
1108
1119
1120
1092
1113
1117
1121
Upvotes: 2
Views: 177
Reputation: 320571
Your code obviously prints only those indices, for which table[table_index]
is not null. If table[0]
is null, it will never print 0
. I.e. this code does not necessarily demonstrate the behavior of rand()
. Instead it's behavior might be mostly determined by the content of table
.
Upvotes: 1