FreeStyle4
FreeStyle4

Reputation: 282

Sort Linked List alphabetically

I'm trying to sort my list alphabetically but i'm having some issues. I have the following:

    struct listNodeData
        {
            int value;
            char *position;
            char *lastName;
            struct listNodeData * next;
        };
        typedef struct listNodeData listNodeData;

void sortList(listNodeData *List)
{
    int swapped;
    listNodeData *ptr1;
    listNodeData *lptr = NULL;

    do
    {
        swapped = 0;
        ptr1 = List->next;

        while (ptr1->next != lptr)
        {
            if (strcmp(ptr1->lastName,ptr1->next->lastName) > 0)
            {
                swap(ptr1,ptr1->next);
                swapped = 1;
            }
            ptr1 = ptr1->next;
        }
        lptr = ptr1;
    }
    while (swapped);

}

void swap (listNodeData *a,listNodeData *b)
{

    char *lastName = malloc(sizeof(char) * 20);
    strcpy(lastName,a->lastName);
    strcpy(a->lastName,b->lastName);
    strcpy(b->lastName,lastName);

}

I am trying to sort the linked list by last name. Right now i'm just trying to swap the last names of my nodes before worrying about swapping the value and position along with the last name. When I compile my program, it works when I run it I get Bus error 10.

I'm not exactly sure why im getting bus error. I've looked at it, and it might have something to do with my strcmp? I'm not sure why because i malloced lastName when I initialized my node, and am mallocing inside the swap function.

The linked list has a dummy header node, so thats why I have ptr1 = List->next instead of ptr1 = List

listNodeData *initNode(int number,char *lastName,char *position)
{
    listNodeData *newNode;
    newNode = malloc(sizeof(listNodeData));
    newNode->position = malloc(sizeof(char) * 20);
    newNode->position = position;
    newNode->lastName = malloc(sizeof(char) * 20);
    newNode->lastName = lastName;
    newNode->value = value;
    newNode->next = NULL;
    return (newNode);
}

Upvotes: 1

Views: 7121

Answers (2)

amrender singh
amrender singh

Reputation: 8239

There is no space allocated for the string in swap function.

Try this:

char*  lastName = (char*) malloc(20*sizeof(char));

Upvotes: 0

Dennis Shtatnov
Dennis Shtatnov

Reputation: 1363

In you initialization code,

newNode->lastName = malloc(sizeof(char) * 20);
newNode->lastName = lastName;

This does not use the buffer you malloc'ed. Instead it replaces the pointer to the buffer with the lastName given to the function. Use a strcpy to move the lastname into the buffer:

strcpy(newNode->lastName, lastName);

Note: Similarly there is the same issue with the position property so this needs to be done for both.

Some other issues to note:

  • Don't forget to free(lastName) at the end of swap to not produce a memory leak in the swap

Upvotes: 1

Related Questions