Thread: Linked list trouble

  1. #1
    Join Date
    May 2004

    Linked list trouble

    I'm getting a seg fault and I can't work out why.

    int add_node(void){
      struct list *temp;
      // Go to end of list
      current = &head;
          current = current->next;
      else return 1;
      // Allocate memory
      temp = malloc(sizeof(struct list));
        return 1;
      temp->next = NULL;
      //current->next = temp;    /* This line gives me the seg fault */
      return 0;
    It looks good to me but it's late and I can't work out why this isn't working. If more code is needed, just ask.

    nevermind, I fixed it. (I seem to do this a lot dont I?)
    Last edited by sand_man; 02-06-2005 at 09:07 AM.

  2. #2
    Registered User penney's Avatar
    Join Date
    Jan 2003

    current is null

    The reason for your error is because you are looping through current while there is a current. Therefore, it will be null after the loop finishes. You need to keep a pointer to the last thing prior to it going null. Lastly, you should check that current is valid prior to attempting an assignment.

  3. #3
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    penney is right. If you want to go to the end of the list you must use loop like this:
    while ( current->next )
           current = current->next; 
    What are you trying is to dereference null pointer and that is seg fault!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  2. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  3. How can I traverse a huffman tree
    By carrja99 in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 05:46 PM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM