2

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.

1 Answer 1

4

Your loop test is incorrect:

while(strcmp(key,a[j]) == -1 && j>=0){

You should check the index j before using it and you should not rely on strcmp() returning -1 for key less than a[j]. strcmp() is only specified as returning a negative value for this case.

while (j >= 0 && strcmp(key, a[j]) < 0) {
Sign up to request clarification or add additional context in comments.

3 Comments

You are hitting on all 8-cylinders today!
@DavidC.Rankin: procrastinating on some more important work is such an incredibly effective motivation ;-)
@yhsdygdyusgdysgdsudsd: can you please accept this answer by clicking on the grey checkmark below the answer score?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.