0

I am working on a program that takes an arbitrary number of arguments from the command line, cuts them in half, puts them in an array, sorts them alphabetically, then prints them in order. It works fine up to three arguments, but is giving some strange output after that. Output Here is what I have so far:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct string {
    char *first_half;
    char *second_half;
};

int cstring_cmp(const void *a, const void *b);
int arrayIndex = 0;

int main(int argc, char *argv[])
{
    int numArguments = argc; 
    char **new_array = malloc(argc * sizeof(char*));
    struct string word;

    for (int i = 1; i < argc; i++) 
    {
        int len = strlen(argv[i]);
        int len_first = len/2;
        int len_second = len - len_first;

        word.first_half = malloc( (len_first + 1) * sizeof(char) );
        word.second_half = malloc( (len_second + 1) * sizeof(char) );

        memcpy(word.first_half, argv[i], len_first);
        memcpy(word.second_half, argv[i]+len_first, len_second);

        new_array[arrayIndex] = word.first_half;
        if(word.second_half != " ")
            new_array[arrayIndex+1] = word.second_half;

        arrayIndex += 2;

        //free(word.first_half);
        //free(word.second_half);
    }

    qsort(new_array, ((argc - 1)*2), sizeof(char *), cstring_cmp);

    for (int i = 0; i < ((argc - 1)*2); ++i)
    {
        printf("%s\n", new_array[i]);
    }

  return 0;
}

int cstring_cmp(const void *a, const void *b) 
{ 
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
} 
2
  • Please do include those strange outputs in the post. Commented Sep 30, 2019 at 1:46
  • Just added it, thank you. Commented Sep 30, 2019 at 2:11

1 Answer 1

1

You are not setting the last characters for word.first_half and word.second_half to '\0'. Therefore the comparison function will have undefined behavior in the call strcmp and so will printf, because both of them expect pointers to null-terminated strings.

Also you are not allocating enough for new_array. It will have to contain twice argc-1 elements.

if(word.second_half != " ") also causes problems should it not trigger, because you are leaving the position in new_array that would be filled uninitialized, and so the functions mentioned above will get invalid pointers.

Sign up to request clarification or add additional context in comments.

Comments

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.