Search code examples
cstructlinked-listsingly-linked-listfunction-definition

Segmentation fault in alphabetical linked list in C


I have a segmentation fault occurring in my alphabetical linked list and I pinned it down to the prev in the last else statement.

else 
{
    prev->next = new_node;
    new_node->next = ptr;
    return 0;
}

How do I fix this issue?

int add(char *str, char *file) {
struct word_node *new_node = malloc(sizeof(struct word_node));

unsigned len = strlen(str) + 1;
char *s = malloc(len);
memcpy(s, str, len);

new_node->data = s;
new_node->count = 1;
new_node->filename = file;
new_node->next = NULL;

// struct word_node 

if (head == NULL)
{
    head = new_node;
    return 0;
}

struct word_node* ptr = head;
struct word_node* prev = NULL;

while (ptr != NULL)
{
    if (strcmp(ptr->data, new_node->data) > 0)
    {
        break;
    }
    ptr = ptr->next;
}

if (ptr == head)
{
    new_node->next = head;
    head = new_node;
    return 0;
}
else 
{
    prev->next = new_node;
    new_node->next = ptr;
    return 0;
}
}

Solution

  • In this while loop

    while (ptr != NULL)
    {
        if (strcmp(ptr->data, new_node->data) > 0)
        {
            break;
        }
        ptr = ptr->next;
    }
    

    you forgot to update the pointer prev as for example

    while (ptr != NULL)
    {
        if (strcmp(ptr->data, new_node->data) > 0)
        {
            break;
        }
        prev = ptr;
        ptr = ptr->next;
    }