Linked list trouble

This is a discussion on Linked list trouble within the C Programming forums, part of the General Programming Boards category; I'm getting a seg fault and I can't work out why. Code: int add_node(void){ struct list *temp; // Go to ...

  1. #1
    ---
    Join Date
    May 2004
    Posts
    1,379

    Linked list trouble

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

    Code:
    int add_node(void){
      struct list *temp;
    
      // Go to end of list
      current = &head;
      if(current){
        while(current){
          current = current->next;
        }  
      }  
      else return 1;
          
      // Allocate memory
      temp = malloc(sizeof(struct list));
      if(!temp)
        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.


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

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

    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
    Posts
    712
    penney is right. If you want to go to the end of the list you must use loop like this:
    Code:
    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, 08:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21