I'm trying to adapt my number sorting insertion sort code to sort an input file of strings instead e.g:
thickness
combed
revocable
escorted
However I get a segmentation fault(core dumped) when trying to run the below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 80
#define ARRAY_LEN 10000
void insertion_sort(char **a, int n) {
int i;
int j;
char *key;
for (i = 1; i < n; i++) {
key = a[i];
j = i - 1;
while (strcmp(key, a[j]) == -1 && j >= 0) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
int main(void) {
int j;
int num_words = 0;
char word[STRING_LEN];
char *wordlist[ARRAY_LEN];
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++;
}
insertion_sort(wordlist, num_words);
for (j = 0; j < num_words; j++) {
printf("%s\n", wordlist[j]);
}
return EXIT_SUCCESS;
}
I've found by changing the while condition to > 0 instead of >= 0
while (strcmp(key, a[j]) == -1 && j > 0)
It sorts everything but the first string, as this is when j is 0 and the loop isn't entered, and the output is:
thickness
combed
escorted
revocable
I'm new to C and I gather this is related to accessing memory that hasn't been allocated, but I'm struggling to see where.