1

I have done basic implementation of Linked List but its giving Segmentation fault on uncommenting the commented lines otherwise its working fine. I am not able to understand why its giving the error. Please give me some help

void insert(Node **head, Symbol sym) {
    Node *temp, *p = *head;;
    Symbol a = sym;
    temp = (Node *)malloc(sizeof(Node));
    temp->value = a;
    temp->next = NULL;

    if (p == NULL)
        *head = temp;
    else {
        while (p->next != NULL)
            p = p->next;
        p->next = temp;
    }
}

void printList(Node *head) {
    Node *p = head;
    if(p == NULL) return;
    while (p != NULL) {
        printf("%d ", p->value);
        p = p->next;
    }
    printf("\n");
}
int main() {
    Node *List, *list2;
    insert(&List, 0);
    insert(&List, 1);

    //insert(&list2, 2);
    //insert(&list2, 3);

    printList(List);
    return 0;
}
3
  • 1
    Please use a debugger like gdb and step through. Commented Mar 18, 2015 at 9:30
  • 10
    Node *List=NULL, *list2=NULL; Commented Mar 18, 2015 at 9:32
  • Apart from personal development or an application where the additional bytes per node and processing steps per function needs to be kept low. Should people not be using GList from the GObject library or something similar Commented Mar 18, 2015 at 15:19

1 Answer 1

3

You did not initialize initial pointers to nodes

Node *List, *list2;

Write

Node *List = NULL, *list2 = NULL;

Take into account that variable list2 is not used in the program you showed.

The other way to write function insert is the following

void insert( Node **head, Symbol sym ) 
{
    Node *temp = malloc( sizeof( Node ) );

    if ( temp != NULL )
    {
        temp->value = sym;
        temp->next  = NULL;

        while ( *head ) head = &( *head )->next;
        *head = temp;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Paul Ogilvie Does it mean that I may not give my own answer?:)
It would have been nice if you referenced Bluepix to give him the credit of the solution.
@Paul Ogilvie Oh, I am sorry. When I was writing my post I had not seen yet the comments.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.