The program finds the average length of words in a given input and prints the words greater than the average. Here's the program
#define STRING_LEN 80
#define ARRAY_LEN 3
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
void numbers_greater(char **wordlist, int average, int n){
if(n < ARRAY_LEN){
int a = strlen(wordlist[n]);
if(a>average){
printf("%s", wordlist[n]);
}
numbers_greater(wordlist+1, average, n+1);
}
}
int main(void) {
char word[STRING_LEN];
char *wordlist[ARRAY_LEN];
int num_words;
double average;
int i;
while (num_words < ARRAY_LEN && 1 == scanf("%79s", word)) {
wordlist[num_words] = emalloc((strlen(word) + 1) * sizeof wordlist[0][0]);
strcpy(wordlist[num_words], word);
num_words++;
}
average = 0.0;
for (i = 0; i < num_words; i++) {
average += strlen(wordlist[i]);
}
average = average / num_words;
printf("%f\n", average);
numbers_greater(wordlist, average, 0);
for (i = 0; i < num_words; i++) {
free(wordlist[i]);
}
return EXIT_SUCCESS;
}
The program works up until the "numbers_greater" method, giving a segmentation fault error. I'm new to C so I'm a little bit confused, the recursive method runs without an error without the strlen statement, but with the strlen statement (even if I set it to a static number like 2) it bombs out of the code. Am I traversing through the array incorrectly?
num_wordsis uninitialized.