Search code examples
cstrcmpqsort

qsort segmentation fault


So I'm working on a program where the function reads in from stdio, and keeps reading in characters in chunks of n characters.

So far I've gotten it so that everything is stored in a character array called buffer. For the next step, I need to sort each chunk of n characters. For example the string cats/ndogs/n should be split as cats/n dogs/n if n =5, and then qsort() needs to alphabetize it. This is how I'm calling qsort():

qsort (buffer, (line-2)*n*(sizeof(char)),n,compare);

Where (line-2)*n*sizeof(char) gives the total number of items in the array buffer; 10 in this case.

This is my compare function:

int compare (const void * a, const void * b)
{
   return (strcmp(*(char **)a, *(char **)b));
}

When I run this, however, I always get a seg fault in strcmp(). Any ideas why?


This is the loading code:

while (!feof(stdin))
{
    for (i = 0; i < n; i++)
    {
        char l = getchar();
        if (l != EOF)
        {
            if ((i == 0) && (line != 1))
            {
                success = (int *)realloc(buffer, line*n*(sizeof(char)));
            }
            buffer[(n*(line-1))+i] = l;
        }
     }
     line = line + 1;
}

Solution

  • Silly question, but are your strings null terminated? You seem to only have a newline on the end.

    Also, you probably only need "strcmp((char *)a, (char *)b)" as the extra *s look to be redundant to me.