Ginormous
Ginormous

Reputation: 13

Getting strange output when printing sorted array in C

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);
} 

Upvotes: 0

Views: 35

Answers (1)

walnut
walnut

Reputation: 22152

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.

Upvotes: 1

Related Questions