7 #define DICT "/usr/share/dict/linux.words"
8 #define STARTING_SZ 8192
9 #define MAX_ARRAY_SZ 1073741824
17 static int alloc_dict(struct dict **d, int array_sz)
21 if (array_sz > MAX_ARRAY_SZ) {
22 fprintf(stderr, "can't allocate a words array bigger "
23 "than %d\n", MAX_ARRAY_SZ);
27 num_bytes = sizeof(struct dict) + (array_sz * sizeof(char*));
28 nd = realloc(*d, num_bytes);
30 fprintf(stderr, "failed to realloc to size %d\n",
36 nd->array_sz = array_sz;
40 static struct dict* read_dict(FILE *fp)
44 malloc(sizeof(struct dict) + (STARTING_SZ * sizeof(char*)));
46 fprintf(stderr, "failed to allocate dict\n");
50 d->array_sz = STARTING_SZ;
53 if (! fgets(word, sizeof(word), fp)) {
56 fprintf(stderr, "%s: error reading line %d: "
58 __func__, d->num_words + 1,
65 d->words[d->num_words] = strdup(word);
66 if (!d->words[d->num_words]) {
67 fprintf(stderr, "failed to allocate word %d\n",
73 if (d->num_words >= d->array_sz) {
74 if (alloc_dict(&d, d->array_sz * 2)) {
82 static const char* choose_random_word(struct dict *dict)
84 int choice = random() % dict->num_words;
86 return dict->words[choice];
96 gettimeofday(&tv, NULL);
97 srandom(tv.tv_usec * tv.tv_sec);
99 fp = fopen(DICT, "r");
102 fprintf(stderr, "failed to open %s: %s (%d).\n",
103 DICT, strerror(err), err);
106 dict = read_dict(fp);
111 word = choose_random_word(dict);