I wrote a function to sort a string in alphabetical order but getting a segmentation fault

Viewed 52

sort and swap functions take pointer as argument, when I try it with 2 or 3 strings it works fine but for more than three its giving a segmentation fault, this is my code please let me know what's going on here and why it's giving this error.

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

void get(int r, int c, char (*s)[c]);
void print(int r, int c, char (*s)[c]);
void sort(int r, int c, char (*s)[c]);
void swap(int c, char (*s)[c], char (*s1)[c]);
void main()
{
    int r;
    printf("\n\t enter no. : ");
    scanf("%d", &r);
    char s[r][31];
    get(r,31,s);
    sort(r,31,s);
    printf("\n\tsorted list");
    print(r,31,s);
}
void get(int r, int c, char (*s)[c])
{
    int i, j;
    for(i = 0; i < r; i++)
    {
        printf("\n\t");
        scanf("%s", *(s+i));
    }
}
void print(int r, int c, char (*s)[c])
{
    int i, j;
    for(i = 0; i < r; i++)
    {
        printf("\n\t%s", *(s+i));
    }
}
void sort(int r, int c, char (*s)[c])
{
    int i, j, k;
    for(i = 0; i < r; i++)
    {
        for(j = 0, k = 1; j < r-1; j++, k++)
        {
            if(strcmp(*(s+j),*(s+k)) > 0)
            {
                swap(c, (s+j), (s+k));
            }
        }
    }
}
void swap(int c, char (*s)[c], char (*s1)[c])
{
    char (*t)[c];
    strcpy(*t, *s);
    strcpy(*s,*s1);
    strcpy(*s1,*t);
}
1 Answers

t is a pointer and as such it needs to be initialized, that is the reason for the segmentation fault, you need to allocate and assign the needed memory though a way better solution would be to simply make it an array:

void swap(int c, char (*s)[c], char (*s1)[c])
{
    char t[c];
    strcpy(t, *s);
    strcpy(*s,*s1);
    strcpy(*s1,t);
}

Or

char (*t)[c] = malloc(sizeof *t); // you'll need stdlib.h

With this second option you must free the memory:

free(t);

I would strongly advise the first solution though.

I would also strongly advise the use of a width limiter for the scanf in your get function, otherwise you are at risk of buffer overflow and consequently of undefined behavior.

scanf("%30s", *(s+i));
// discard extra characters in case the input is larger than the destination buffer
while ((c = getchar()) != '\n' && c != EOF){}

Note that main return type should be int.

Live sample

Related